2016-12-15 123 views
0

目前我有两个输入字段,当我按下更新按钮时自动更新,我想添加更多的输入......但问题是我必须手动添加我的输入字段名称在jQuery脚本。 我们可以为此添加任何循环吗?请帮忙!!jQuery循环的复选框

Type Comment: <input name="mainComment" type="text" value="" /> 
<input type="button" name="updateComment" value="Update" /> 

<hr /> 

<input type="checkbox" class="myCb" name="cb[1]" /><input type="text" name="inv[1]" value="" /><br /> 
<input type="checkbox" class="myCb" name="cb[2]" /><input type="text" name="inv[2]" value="" /> 


<script type="text/javascript"> 
    $(document).ready(function() { 
     $("input[name='updateComment']").live("click", (function(){ 
      if($("input[name='cb[1]']").is(":checked")) { 
       $("input[name='inv[1]']").val($("input[name='mainComment']").val()); 
      } else { 
       $("input[name='inv[1]']").val(""); 
      } 

      if($("input[name='cb[2]']").is(":checked")) { 
       $("input[name='inv[2]']").val($("input[name='mainComment']").val()); 
      } else { 
       $("input[name='inv[2]']").val(""); 
      } 
     })); 
    }); 
</script> 
+0

['.live()'](http://api.jquery.com/live/)已被弃用,并在较新的jQuery版本中被删除。我会建议更新你的脚本到['.on()'](http://api.jquery.com/on/) – empiric

+0

Thankyou @empiric –

回答

1

可以使用输入的class name.myCb)来选择从DOM输入和通过每个输入使用jQuery的.each()方法来循环。

你可以这样说:

$(document).ready(function() { 
 
     $("input[name='updateComment']").on("click", (function(){ 
 
     \t \t var val = $("input[name='mainComment']").val(); 
 
      $('input.myCb').each(function(i) { 
 
      \t if($(this).is(':checked')) { 
 
       $(this).next().val(val); 
 
       } else { 
 
       $(this).next().val(''); 
 
       } 
 
      }) 
 
     \t \t 
 
     
 
     })); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Type Comment: <input name="mainComment" type="text" value="" /> 
 
<input type="button" name="updateComment" value="Update" /> 
 

 
<hr /> 
 

 
<input type="checkbox" class="myCb" name="cb[1]" /><input type="text" name="inv[1]" value="" /><br /> 
 
<input type="checkbox" class="myCb" name="cb[2]" /><input type="text" name="inv[2]" value="" /><br> 
 
<input type="checkbox" class="myCb" name="cb[3]" /><input type="text" name="inv[2]" value="" />

希望这有助于!

+0

它工作正常。非常感谢 :) –