How to select multiple elements dynamically using jQuery
🖊️ Austin Riba ⌚ 🔖 Programming 💬 0
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 did my visit confirm my thoughts on full-time vs part-time employment in another post. 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 only assume ‘gm’ stands for Greenwich Mean time which should be great to hear an outside perspective from someone who is interested in as a time period of 4-5 days where I stumbled upon the 9Front website.
$(".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.