matt
matt

Reputation: 62

JQuery .on only firing once on dynamically generated elements

So I have the following problem. I am trying to add a two events to a table of checkboxes.

Here's an example of the html.

<body>
<div id='container'> //static element, everything beyond this element is dynamic
 <div id='pane_x'>
  <div id='bottom_x'>
   <div id='bottom_left_x'>
    <div id='results_x'>
     <div id='list_x'>
      <div id='table_1'>
       <table>
        <tbody>
         <tr>
          <td>
           <input type='checkbox' name='blah' id='blah_obj.id_x' class='blahblah'>
          </td>
         </tr>
        </tbody>
       </table>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

I am trying to select the checkboxes only hopefully by using a prefix selector [id^='blah_']. I am able to get the code working for the first pane ie: pane_0, but it doesn't fire on pane_1 or beyond.

jquery(document).on("change", "[id^='blah_" + obj.id + "']", function() {
//code here
});

There may be nesting errors as I just made an approximate estimate of the html. The weird thing is I can see them by using a daisy chained .children() statement, but I can't select the input elements.

Since the comments don't support the same code blocks as this section I'll just add it here:

jquery(document).on("change", ".checked", function() {
 var ids = jquery(this).attr("id").split("_");
 if (ids[0] === "blah")
  //do code
 }
});

edited the id for clarity. The id structure is "blah_" obj.id "_" individual iterator. So 3 checkboxes on pane 0 would look like this: blah_0_0 blah_0_1 blah_0_2

there are 2 other sets of checkbox lists on this page that I do not want to target with these functions, that is why i'm using the prefix selector.

Upvotes: 1

Views: 309

Answers (2)

charlietfl
charlietfl

Reputation: 171689

The point of using startsWith selector is not to try to complete the whole value as you are doing with obj.id if obj.id is even defined.

Following would find all input with ID's starting with 'blah_' either existing or in the future.

jQuery(document).on("change", "input[id^='blah_']", function() {
//code here
});

Using the class as selector makes even more sense if they all share a common class

jQuery(document).on("change", "input.blahblah", function() {
//code here
});

Also note you have typo in jquery should be jQuery unless you have defined it otherwise in your own code

Important note ID's may not be repeated in a page, in case you have been repeating the same checkbox ID. They must be unique by definition

Upvotes: 1

solisoft
solisoft

Reputation: 669

here another sample :

$("body").on({
    click:function(){
        // where $(this) is the current item changed
    }
}, "input.blahblah");

Upvotes: 0

Related Questions