1

I have a list of items and I want to do something whenever one of the items is selected, but the problem is that the check-box's change function is not working with me.

I have checked the code inside the function and it's working fine outside the change event. i'm not sure of the reason why it's not working but what could it be other than the function its self ?

Here the change function:

$("input[name='checkCoResult']").change(function () {
     if (this.checked) {
        $("#searchResultSecond").attr("style", "opacity: 0.6");
        $("#searchResultSecond *").attr("disabled", "disabled").off('click');
     }

});

and this is the code that generate my list:

$.ajax({
        url: "CCDMSWebService.asmx/getCoSearchResult",
        data: JSON.stringify(objectData),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
             var Result = response.d;
                 contantDiv.text("");
        $.each(Result, function (index, val) {
            contantDiv.append('<div  class="panel-bod"><label style="margin:2px; border-radius: 10px;border: 1px solid #cc0000;padding: 5px;"><input type="checkbox" value="' + val.companyID + '" name="checkCoResult" class="nnn"> '
        +'<img src="images/' + val.companyID + '.png" alt="company logo" width="30%" height="30%">' + val.companyName + ' provides all your needs</label></div>');
           })
        },
        failure: function (msg) {
        alert(msg);
       }
    });
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
Nysa
  • 425
  • 1
  • 5
  • 14

2 Answers2

1

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). In your case it seems you already have a div named contantDiv present in your page, so modify your code like

contantDiv.on("change","input[name='checkCoResult']",function(){ ...

Check out http://api.jquery.com/on/#direct-and-delegated-events for more details.

Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
-1

if your content is dynamic then try

$(document).on("change","input[name='checkCoResult']",function(){
     // your code
});
user3737317
  • 72
  • 12
  • thank you so much. but why is this one working while the jquery not? I just want to understand to avoid similar problems. – Nysa Jun 18 '16 at 21:00
  • Binding to document should only be a last resort. Better to use closest parent which exists at time event is bound: http://stackoverflow.com/a/12824698/1767412 – But those new buttons though.. Jun 18 '16 at 21:30