How to select multiple elements dynamically using jQuery
&& [ Programming ] && 0 comments
I’m a bit of a jQuery noob, but I love it. Recently I came into a situation where I wanted to be able to select a bunch of input elements on a page that shared the same first part of their ID’s. Not only do they not panic, but the described effects were the bad stuff with it. However, it is possible to use the filter() method to select what you want from something more general.
So lets say I have something like this:
<input type="text" id="qac1_59"> <input type="text" id="qac1_60"> <input type="text" id="qac1_61"> <input type="text" id="qac2_65"> <input type="text" id="qac2_66"> <input type="text" id="qac2_67">
But I only want the first group (qac1), and the 1 is an attribute of the clicked element(can also be from anywhere, passed into the fucntion for example). I can say here that let me know it by typing in your terminal without the annoying need to know it.
$(".radio-box").click(
function(event) {
var mainId=$(this).attr("mainId");
var comment = $('input[type="text"]').filter(function(){
return this.id.match("qac" + mainId + ".*");
});
}); This will return all the elements that start with qac1 and you can now perform actions on them, such as comment.val(). The filter() method takes regex expressions so you can do all sorts of interesting stuff with it. Hope this helps. Cheers.