开发者

Jquery Form field duplication

I have quite a long complicated php form, and a requirement to duplicate a set of fields. I am sure there must be a more efficient way of coding it, however I can't figure it out. There are 2 examples (of over 15) below where the only things that change are the IDs i.e. #PN etc. Is there possibl开发者_如何学Cy a way to loop through the fields?

$(document).ready(function(){
            $("#PN1").click(function(){
            if ($("#PN1").is(':checked')) {
             // Checked, copy values  
             $("#PNevent1").val($("#PNevent0").val());  
             $("#PNroom1").val($("#PNroom0").val());  
             $("textarea#PNdescription1").val($("textarea#PNdescription0").val());  
             $("select#PNmenu1").val($("select#PNmenu0").val());  
             $("#PNdate1").val($("#PNdate0").val());  
             $("#PNtimestart1").val($("#PNtimestart0").val());  
             $("#PNtimeend1").val($("#PNtimeend0").val());  

} else {
// Clear on uncheck
             $("#PNevent1,#PNroom1,textarea#PNdescription1,select#PNmenu1,#PNdate1,#PNtimestart1,#PNtimeend1").val(""); 
            }
            });

$("#PN2").click(function(){
            if ($("#PN2").is(':checked')) {
             // Checked, copy values  
             $("#PNevent2").val($("#PNevent1").val());  
             $("#PNroom2").val($("#PNroom1").val());  
             $("textarea#PNdescription2").val($("textarea#PNdescription1").val());  
             $("select#PNmenu2").val($("select#PNmenu1").val());  
             $("#PNdate2").val($("#PNdate1").val());  
             $("#PNtimestart2").val($("#PNtimestart1").val());  
             $("#PNtimeend2").val($("#PNtimeend1").val());  

} else {
            // Clear on uncheck
             $("#PNevent2,#PNroom2,textarea#PNdescription2,select#PNmenu2,#PNdate2,#PNtimestart2,#PNtimeend2").val(""); 
            }
            });
});


use the pseudo selector :first to ensure that the selectors arn't being duplicated


Since the selectors are just strings, you could do something like:

for(var i = 1; i < 15; i++) {

     $("#PN" + i).click(function(){
         if ($("#PN" + i).is(':checked')) {
              // Checked, copy values  
              $("#PNevent" + i).val($("#PNevent + (i-1)").val());  
              $("#PNroom" + i).val($("#PNroom + (i-1)").val());  
              $("textarea#PNdescription" + i).val($("textarea#PNdescription" + (i-1)).val());  
              $("select#PNmenu" + i).val($("select#PNmenu" + (i-1)).val());  
              $("#PNdate" + i).val($("#PNdate" + (i-1)).val());  
              $("#PNtimestart" + i).val($("#PNtimestart" + (i-1)).val());  
              $("#PNtimeend" + i).val($("#PNtimeend" + (i-1)).val());  
         }
     }); 
}

not sure if this syntax will work exactly, but the idea should.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜