JQuery Checkbox generation

Posted by Hash on Stack Overflow See other posts from Stack Overflow or by Hash
Published on 2010-06-07T05:07:22Z Indexed on 2010/06/07 5:12 UTC
Read the original article Hit count: 228

Filed under:
|
|

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\"/>");
     }
    });
});

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about checkbox