Search code examples
phpjquerydhtml

jquery append with checkbox, if checked, it wont return anything?


I have dynamically generated a list of wine types from the database using AJAx and PHP here is the function

function wineTypeHandler(data){
            var Type = data.Type;
            var countType = data.countType;
            for(var i = 0; i < countType; i++){

                $("#selectType").append(

                $("<input />").attr({
                  type: 'checkbox',
                    name: 'Type',
                    class: 'wineTypeCheck',
                     value: Type[i]
                  }), Type[i] + "<br />"
            );
            }   
        }

As you can see I have "appended" the results to some div with id selectType, this whole thing works fine, my only problem is when I want to update another list based on what has been checked from this list, it doesnt respond to anything!. When i try this one and many other ways

$(document).ready(function(){

$(':checkbox').click(function(){
alert('started');

    // other code
        return true;

});

});

It doesnt alert anything!! Can anybody help me with this problem.

thank you in advance.


Solution

  • .click() attaches itself to elements that exist when the DOM is created. Your elements are being dynamically generated, so .click() doesn't actually get applied to them.

    You should use .live() to target dynamically generated elements, as it attaches itself to any element that is created after the DOM is initially loaded. I also suggest using the change event instead of a click:

    $(':checkbox').live('change', function(){
      // No need to return true;
    });