How to select multiple elements dynamically using jQuery

🖊️ 🔖 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 that but it had to be dynamic - that first part of the Id had to be stored as a variable rather than be hardcoded. jQuery’s selectors, like input[] do not allow you to use variables. 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 do this:

$(".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.