开发者

JQuery Checkbox generation

开发者 https://www.devze.com 2023-01-02 18:05 出处:网络
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

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.preventDe开发者_StackOverflow社区fault();

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


Use the .live jquery command.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号