I want to make a generic function in jquery for select all functionality. I have a tabbed view in my web page.
Id of my component is : tabId:someDynamicId:rowId:componentId where, someDynamicId is dynamically generated.
So in jquery i want to find the element whose id starts with - tabId:someDynamicId & ends with componentId. And, tabId, someDynamicId & componentId would be passed as an argument to the generic function where this element needs to be find.
It's simple:
$('[id^=tabId][id$=componentId]').each(function(){
var id = $(this).attr('id'); // tabId:someDynamicId:rowId:componentId
var list = id.split(':');
console.log(list[0]); // tabId
console.log(list[1]); // someDynamicId
console.log(list[2]); // rowId
console.log(list[3]); // componentId
})
Wildcards in jQuery selectors
But i'm recommending to use right tools for this job. ID's are useful for finding specific element, but in your case it's better to use one or two classes and data attributes. For example:
<div class="tabs" data-component-id="x" data-tab-id="y">
Then find all $('.tabs') elements and use $(this).data('component-id') and $(this).data('tab-id')
$('.tabs').each(function(){
var component_id = $(this).data('component-id');
var tab_id = $(this).data('tab-id');
});
Update:
There is example of using this as function:
function(tabId,componentId) {
$('[id^='+tabId+'][id$='+componentId+']').each(function(){
var id = $(this).attr('id'); // tabId:someDynamicId:rowId:componentId
var list = id.split(':');
console.log(list[0]); // tabId
console.log(list[1]); // someDynamicId
console.log(list[2]); // rowId
console.log(list[3]); // componentId
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With