0

I want to setup a jquery function on each html element. Since each element has a unique id, I use a for loop:

function setupSwitch(temperatureNumArr){
  var id = '';
  for (var i = 0; i < temperatureNumArr.length; i++) {
    id = 'temperature_switch_'+temperatureNumArr[i]
    $(id, function(){
        console.log(id);
      $(id).change(function() {
        alert(($(this).prop('checked')) + typeof(($(this).prop('checked'))))
      });
    });
 }

the above code only prints the last id, and the on change function fails, I think it is caused by javascript function scope, but I am not sure how to pass id into the $(...) on change function.

Nirav Joshi
  • 2,924
  • 1
  • 23
  • 45
Deidara
  • 667
  • 2
  • 13
  • 28

1 Answers1

0

I'm not entirely sure why you are attempting to bind the change handler in this fashion.

Suggestion, add a CSS class to your checkboxes say "tempSwitch", then your jquery setup should be as follows:

$("input:checkbox.tempSwitch").change(function() {
    var id = $(this).attr('id');
    alert(id + ": " + ($(this).prop('checked')) + typeof(($(this).prop('checked'))))
});

The $("input:checkbox.tempSwitch") will locate all inputs of type checkbox with the CSS class tempSwitch and attach a 'change' handler for when they are changed.

Dave G
  • 9,639
  • 36
  • 41