Laziale
Laziale

Reputation: 8225

Detect checkbox checked unchecked with jQuery

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.

Upvotes: 0

Views: 1584

Answers (3)

Deepak Ingole
Deepak Ingole

Reputation: 15742

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.

Upvotes: 4

sshet
sshet

Reputation: 1160

Try to code using on event

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

Upvotes: 1

Maurice Perry
Maurice Perry

Reputation: 32831

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() : "");
});

Upvotes: 1

Related Questions