BobbyDigi
BobbyDigi

Reputation: 55

add click event to multiple dynamically created elements with matching classes

I need to create a click event so that when a dynamically created button is clicked, a check mark is added to a coinciding checkbox.

I have a group of dynamically created buttons / checkboxes like so:

<dd id="parent1"> 
     <a href="#form"><button>Apply Now</button></a>
</dd>

<ul id="parent2">    
    <li>
        <input type="checkbox" name="CAT_Custom_785591"> 
   </li>
</ul>

I've also incorporated JS so that each dynamically created button / checkbox is given a coinciding class (i.e the first button will be given the class of '.job0' while the first checkbox will also be given the class of '.job0', the second button / checkbox will be '.job1' and so on).

        //set unique classes for buttons and checkboxes
        var $buttonClass = $("#parent1 a");
        $buttonClass.attr('class', function (index) {
            return 'job' + index;
        });
        var $checkBoxClass = $("#parent2 input");
        $checkBoxClass.attr('class', function (index) {
            return 'job' + index;
        });

I've also added JS to tie the click event to the dynamically created buttons:

        $(document).on('click', 'a[class^="job"]', function() {
            console.log('element clicked');
        });

What is the best approach to ensure that all the dynamically created buttons can be clicked and have the coinciding checkbox be checked (once again, when button with class '.job0' is clicked, checkbox with class '.job0' is checked, and so on and so forth for every group of dynamically generated elements)?

Upvotes: 4

Views: 56

Answers (1)

Hikarunomemory
Hikarunomemory

Reputation: 4305

I would prefer setting a data-* attribute to button and input that coinciding with each other with the same value.

$(document).on('click', 'button[class^="job"]', function() {
  console.log('element clicked');
  var id = $(this).data('id')
  $(`input[data-id=${id}]`).prop('checked', true)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dd id="parent1">
  <a href="#form"><button class="job0" data-id="job0">Apply Now</button></a>
</dd>

<ul id="parent2">
  <li>
    <input class="job0" type="checkbox" name="CAT_Custom_785591" data-id="job0">
  </li>
</ul>

If you want it toggle checked state by click button again.

$(document).on('click', 'button[class^="job"]', function() {
  console.log('element clicked');
  var id = $(this).data('id')
  var checked = $(`input[data-id=${id}]`).is(':checked')
  $(`input[data-id=${id}]`).prop('checked', !checked)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dd id="parent1">
  <a href="#form"><button class="job0" data-id="job0">Apply Now</button></a>
</dd>

<ul id="parent2">
  <li>
    <input class="job0" type="checkbox" name="CAT_Custom_785591" data-id="job0">
  </li>
</ul>

Upvotes: 2

Related Questions