views:

31

answers:

1

I have used the following code to generate some dynamic checkboxes. This works for the first time and adds the check box chk2 to the page and then after the trigger for the $('#newLink').click is not working. Please help me with this.

 <div id="chkBoxesDiv">
     <input type="checkbox" id="chk1" ></input>
     <input id="answerText" type="text" size="30" ></input>&nbsp;
     <input type="button" value="add new" id="newLink"/>
 </div>

$(document).ready(function(){

$('#newLink').click(function (event){
    var i = 0;
    //To count the children
    $("#chkBoxesDiv").children().each(function(){
        var child = $(this);
        if(child.is(":checkbox")){
            i++;
        }
     });

     //prevent action
     event.preventDefault();

     //get textbox value to fill checkbox
     var text = $("#answerText").val();
     alert(i);

     //if text not empty do stuff
     if(text != ""){
     //add label
         $("#chk"+i).after("<label for=\"chk"+i+"\" id=\"lblchk"+i+"\">"+text+"</label>");


         $("#newLink").remove();
         $("#answerText").remove();
         $("#lblchk1").after("<br /><input type=\"checkbox\" id=\"chk"+(1+i)+"\" ></input><input type=\"text\" id=\"answerText\" size=\"30\" ></input>&nbsp;<input type=\"button\" value=\"add new\" id=\"newLink\"/>");
     }
    });
});
+1  A: 

Use the .live jquery command.

When you add elements onto the page they don't automatically have click events. You need to assign them

griegs
Thanks brother, it worked !
Hash