0

I'm trying to detect when a checkbox is checked or unchecked in jQuery. I'm creating the checkboxes dynamically from JSON content. This is how they are created:

$.each(data.modifierOptions, function(key, item) {
                            var checkBox = "<input type='checkbox' class='modifier' data-name='" + item.Name + "' + data-price='" + item.Price + "' name='" + item.Name + "' value='" + item.ID + "'/>" + item.Name + "<br/>";
                            $(checkBox).appendTo('#modifiersDiv');
                        });      

Now, viewing the source of the body I'm getting this:

enter image description here

Finally, I'm trying to get the checked/unchecked event with this jQuery event, but nothing happens:

$('input:checkbox.modifier').change(function () {
            var sThisVal = (this.checked ? $(this).val() : "");
        });

How can I solve this?

Update

I want to get the event by checkbox class.

2
  • use mousedown() event listener instead of change(). Commented Apr 17, 2014 at 16:13
  • 1
    This is asked hundred times a week, at least... Commented Apr 17, 2014 at 16:23

3 Answers 3

4

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .click()

As you are adding a content dynamically you should use,

$(document).on('change', 'input:checkbox.modifier',  function () {
     var sThisVal = (this.checked ? $(this).val() : "");
});

Read about delegating events.

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

Comments

1

As you create dynamically the checkboxes, you would have to setup the event handler like this:

$(document).on("change", "input[type='checkbox'].modifier", function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});

1 Comment

Thanks for edit ..Habit of writing jquery selector inside "" gonna hung me someday..
1

Try to code using on event

 $(document).on('change', 'input:checkbox.modifier',  function () {
        var sThisVal = $(this).is(':checked') == true ? $(this).val() : "";
    });

Comments

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.