Skip to content

Instantly share code, notes, and snippets.

@Fintan
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save Fintan/cb4f997dc4f31b9f21e0 to your computer and use it in GitHub Desktop.

Select an option

Save Fintan/cb4f997dc4f31b9f21e0 to your computer and use it in GitHub Desktop.
When naming of data attributes are not be standardised this method lets me select the element based on a few possibilities
//naming of filters tends to not be standardised so we need to cover a few possibilities
var _selectElement = function($container, selectorTemplate, name) {
var count = 0;
var template = _.template(selectorTemplate);
var $el;
var nameStr;
var strategies = [
function(str) { return str; },
function(str) {return _.str.capitalize(str.toLowerCase())},
function(str) {return str.toUpperCase(); },
function(str) {return str.toLowerCase(); }
];
return function selectEl() {
var areStrategiesExhausted = count > (strategies.length-1);
var wasElementFound;
if(!areStrategiesExhausted) {
nameStr = strategies[count](name);
}
$el = $container.find(template({name: nameStr}));
wasElementFound = $el.length > 0;
if(wasElementFound || areStrategiesExhausted) {
return $el;
}else {
count++;
return selectEl();
}
};
};
//example usage
this.selectElement($('body'), 'input[type=checkbox][data-name=<%= name %>]', option.value)().attr('checked', option.checked);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment