I am trying to detect when a change has occurred on a checkbox(es) but so far have tried with onchange, onclick and [just] click without success. I have 'inherited' the HTML for the checkbox(es) (built via Smarty templates) which are built as per here:-
<input type="checkbox" name="field1[]" id="field1_1" value="80000" />
<label for="field1_1">80000</label>
<input type="checkbox" name="field1[]" id="field1_2" value="80001" />
<label for="field1_2">80001</label>
<input type="checkbox" name="field1[]" id="field1_3" value="80002" />
<label for="field1_3">80002</label>
<input type="checkbox" name="field1[]" id="field1_4" value="80003" checked />
<label for="field1_4">80003</label>
<input type="checkbox" name="field1[]" id="field1_5" value="80004" />
<label for="field1_5">80004</label>
<input type="checkbox" name="field1[]" id="field1_6" value="80005" />
<label for="field1_6">80005</label>
In javascript I declare an object for the checkbox(es) as per here:-
<script>
parent_obj_field1 = document.getElementsByName('field1[]');
</script>
I then declare a 'click' function against that object which itself is intended to run another 'retrieve' function. The later 'retrieve' function carries out an AJAX call based on the value(s) of the checkbox(es) and populates another control.
<script>
parent_obj_field1[0].click = function() {
child_obj_field3_retrieve_data();
}
</script>
I have substituted the 'click' shown here with 'on change' and 'onclick' but to no avail. I have read a number of articles including one that suggests that I might have to add an event listener... but I am not entirely sure of the syntax needed in my case?
Would you advise as to how I fire an event when the user clicks/unclicks any of the boxes in the collection?
Thanks
EDIT
So to expand upon Saurabh Srivastava comment, I have added
parent_obj_field1[0].addEventListener('change', function (event) {alert('changed') });
but do not get an alert when I click any of the boxes? I may be misunderstanding how this works?
field1[]only, if you want to attach it to the rest of the elements, you have to iterate. If you want to attach it to dynamically generated elements gotten with ajax, you have to attach the event handler after the elements are loaded and inserted, or use a delegated event handler, which can be a bit complicated when not using a library (like jQuery).parent_obj_field1[0].addEventListener('change', function (event) { }