5

I cannot detect when and which checkbox gets clicked from script below:

HTML Snippet:

<label for="checkbox[1]"><input type="checkbox" name="checkbox[1]" id="checkbox[1]" class="detectThisChange" value="10.00" checked=""> Amount $10.00</label>
<label for="checkbox[2]"><input type="checkbox" name="checkbox[2]" id="checkbox[2]" class="detectThisChange" value="20.00" checked=""> Amount $20.00</label>
<label for="checkbox[3]"><input type="checkbox" name="checkbox[3]" id="checkbox[3]" class="detectThisChange" value="30.00" checked=""> Amount $30.00</label>

jQuery Snippet:

$(document).ready(function() {
  $(window).load(function() {
// ... //
        $('.detectThisChange').change(function(event){
          var targetID = triggerEvent.target.id; // get the id that triggered the event
          var posStart = targetID.indexOf('[') + 1;
          var posEnd = targetID.indexOf(']');
          var i = targetID.substring(posStart, posEnd); // get the index of the id that triggered the event

          if ( $('#checkbox\\['+ i +'\\]').prop('checked') != true ) {
            alert('checkbox ' + i + ' was checked');
          }
          else {
            alert('checkbox ' + i + ' was unchecked');
          }

        });
// ... //
  }); // end .load()
}); // end .ready()

Appended:

The problem I am experiencing is that none of my alerts work. So that tells me the change() function is not firing.

13
  • 1
    this might help: stackoverflow.com/questions/7919716/… Commented Dec 24, 2014 at 12:08
  • Replace != with == Commented Dec 24, 2014 at 12:11
  • Ok, thanks @97ldave. In the selected answer, what does the id frameName part of jQuery("#frameName").contents() represent? Commented Dec 24, 2014 at 12:13
  • Thank you @BhojendraSah. See my appended comment in my OQ. The change() function is not even firing. Commented Dec 24, 2014 at 12:15
  • Thanks @Invent-Animate. My problem is I cannot get to my change() function. Commented Dec 24, 2014 at 12:16

5 Answers 5

19

If you are adding this HTML dinamically, you should use the .on() method, like:

$(document).on('change', '.detectThisChange', function() {
    // your code
});

Give it a try and let me know if it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

I've fallen into this so many times that it's the first thing I check when it doesn't work.. Glad that helped! :)
This the only way that I could get the .on('change', ... to fire. Works with .on('click',...) also. Others did not. BTW, I was also struck for hours trying to get it to fire using the same method which of course was failing.
7

Try like this

$("input[type=checkbox]").is(":checked") // returns boolean checked or unchecked

   var arr = [];
    $("input[type=checkbox]").each(function () {
        var self = $(this);
        if (self.is(':checked')) {
            arr.push(self.attr("id"));
        }
    });
    console.log(arr);

EdIted:

$("input[type=checkbox]").on('change', function () {
    var self = $(this);
    if (self.is(":checked")) {
        console.log("checkbox  id =" + self.attr("id") + "is checked ");
    } else {
        console.log("Id = " + self.attr("id") + "is Unchecked ");
    }
});

Edited 2 :

$("body").on('change','.detectThisChange', function () {
    var self = $(this);
    if (self.is(":checked")) {
        console.log("checkbox  id =" + self.attr("id") + "is checked ");
    } else {
        console.log("Id = " + self.attr("id") + "is Unchecked ");
    }
});

Working Demo

6 Comments

I need to get my event listener to work first @Satindersingh. Then I am sure your answer will work.
that looks like a new approach. give me a moment to try it @Satindersingh
But I have over 20+ check boxes ion my script @Satindersingh. Is this going to fire on every checkbox when checked?
@H.Ferrence : you can set your selector accordingly like if you want for element having class detectThisChange then use $(".detectThisChange").on('change',function(){});
I did that from the beginning @Satindersingh. That is what caused me to come here to post
|
2

Try on change event with this id selector as 'input[id^=checkbox]':

$(function() {
  $('input[id^=checkbox]').on('change', function() {
    console.log(this.value, this.checked);
  }).trigger('change');//fire event on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="checkbox[1]">
  <input type="checkbox" name="checkbox[1]" id="checkbox[1]" class="detectThisChange" value="10.00" checked="">Amount $10.00</label>
<label for="checkbox[2]">
  <input type="checkbox" name="checkbox[2]" id="checkbox[2]" class="detectThisChange" value="20.00" checked="">Amount $20.00</label>
<label for="checkbox[3]">
  <input type="checkbox" name="checkbox[3]" id="checkbox[3]" class="detectThisChange" value="30.00" checked="">Amount $30.00</label>

2 Comments

thanks @Arvind. It did not work for me even though I know it works for you. I just can't get my change to fire.
@H.Ferrence, any errors on the console? which browser are you using?
2

Try this :

$(".detectThisChange").on('change', function () {

    alert("In the function");
    var targetID = this.id; // get the id that triggered the event
    var posStart = targetID.indexOf('[') + 1;
    var posEnd = targetID.indexOf(']');
    var i = targetID.substring(posStart, posEnd); // get the index of the id that triggered the event

    if ($('#checkbox\\[' + i + '\\]').prop('checked') == true) {
        alert('checkbox ' + i + ' was checked');
    } else {
        alert('checkbox ' + i + ' was unchecked');
    }
});

Here's the JSFiddle, even though you have an answer :)

Comments

0

Try:)

if ( $('#checkbox\\['+ i +'\\]').is(":checked") ) {
  alert('checkbox ' + i + ' was checked');
}
else {
  alert('checkbox ' + i + ' was unchecked');
}

1 Comment

I am sure your answer will work @BhojendraSah once I get the change()function to fire.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.