Add click event to multiple dynamically created elements with corresponding classes

I need to create a click event so that when a dynamically created button is clicked, the check box is added to the matching check box.

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

<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 also enabled JS so that each dynamically created button / checkbox is assigned a matching class (i.e. the first button will be assigned the class '.job0', and the first flag will also be assigned the class '. Job0', the second button / checkbox will be ". job1 ", etc.).

        //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 also added JS to bind the click event to dynamically created buttons:

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

, ( , ".job0", ".job0", .. .. )?

+4
1

data- * , .

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

, , .

$(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>
+2

Source: https://habr.com/ru/post/1696160/


All Articles