If you build web applications, at some point you have built a form that had dynamically named form elements. You loop through a CFQUERY and build some input fields that’s a combination of a string ID and a ColdFusion variable (usually currentRow).
<cfloop query="aSimpleQuery"><cfoutput>
<input type="hidden" id="columnOne_#currentRow#" value="#columnOneValue#">
<input type="hidden" id="columnTwo_#currentRow#" value="#columnTwoValue#">
</cfoutput></cfloop>
I’ve seen a lot of developers struggle with how to then easily identify these fields via Javascript in order to modify/read their values, change the styles, or build a complex data structure from the values.
The power of jQuery’s DOM traverser makes it a snap. It’s just a RegEx expression to find the elements you need. You can also use the built-in function each() for looping over the elements instead of making a for loop.
$("input[id^='columnOne_']").each(function(i) {
if( this.val() != 0 ) {
// Do something really cool here
}
}
At this point, you may be thinking, “Yeah, but what about checkboxes, eh?!? And what if they have name attributes, but no ID??” No problem, just use an even more advanced jQuery selector and the code remains the same.
$("input[name^='columnOne_']:checkbox").each(function(i) {
if( this.val() != 0 ) {
// Do something really cool here
}
}
Take a look-see at all of the jQuery selectors and you’ll see how easy they make it to find DOM elements.
5 Responses for "Find dynamically named DOM elements with jQuery"
Great post! jQuery rocks. :)
Then again, I’m biased since I’m on the project. hehe.
can u help with a small variation of this where i need to detect in a DIV, table with rows which have unique ID (multiple rows with same id too) and hide/show a groupof rows with same ID ?
Thanks in Advance
Regards
Thanks! It was quite helpful.
what is i?
It is the numeric index of each item
Leave a reply