-1

I'm new to JS and just muddling my way through first few scripts. I want to avoid jQuery if possible. I have a set of inline forms (formset in Django language) that make up a form. Each formset in the form contains the same set of fields, and each field uses the following naming format for the field name and ID: name="form--ignore" and id="id_form--ignore".

What I'm trying to achieve is to disable certain fields in each formset if certain checkboxes in the formset are selected.

I've literally written first few lines of code where I've managed to create an event listener. How can I now get the ID of the checkbox that fired the event?

    <script>

        // get all the checkboxes on the page
        var checkboxes = document.querySelectorAll('input[type=checkbox]');

        // add a change event listener
        for(var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].addEventListener('change', function(){
                console.log('Checkbox changed');
            });
        }

    </script>
rcx935
  • 217
  • 5
  • 15

1 Answers1

1

Add this.id inside event listener handler

var checkboxes = document.querySelectorAll('input[type=checkbox]');

// add a change event listener
for (var i = 0; i < checkboxes.length; i++) {
  checkboxes[i].addEventListener('change', function() {
    console.log(this.id);
  });
}
<input type='checkbox' id='1'>
<input type='checkbox' id='2'>
<input type='checkbox' id='3'>
<input type='checkbox' id='4'>
brk
  • 48,835
  • 10
  • 56
  • 78