2015-06-29 37 views
1

的名字,我有HTML顯示覆選框那些通過循環檢查:的Javascript循環得到選中的複選框

<!DOCTYPE html> 

<html> 
    <head> 
     <title></title> 
     <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> 
    </head> 

    <body> 
     <form> 
      <input type="checkbox" name="bla_bla1" id="checkbox_1" onchange="getName();"/> 
      <input type="checkbox" name="bla_bla2" id="checkbox_2" onchange="getName();"/> 
      <input type="checkbox" name="bla_bla3" id="checkbox_3" onchange="getName();"/> 
     </form>  
     <span id="checkboxConfirm_1"></span> 
     <span id="checkboxConfirm_2"></span> 
     <span id="checkboxConfirm_3"></span> 

     <script>    
      function getName(){ 
       for(i = 1; i<4; i++){ 
       var a = "#checkbox_".concat(i.toString()) ; 
       var b = "#checkboxConfirm_".concat(i.toString());    

       if ((a).is(":checked")) { 
        $(b).text($(a).attr("name")); 
       } else { 
        $(b).text(''); 
       } 
      } 
      } 
     </script> 
    </body> 
</html> 

但使用Javascript無法正常工作。請幫我解決問題。

+1

嘗試'如果((一)。是$( 「:勾選」)){' –

+0

使 '一' 查詢對象做$(a) –

回答

2

不要爲每個複選框使用onChange並且不需要使用for循環使用css的正則表達式選擇器,它將解決您的問題。

看看這個例子:http://jsfiddle.net/kevalbhatt18/gpdjoyxx/1/

$('input[type="checkbox"]').change(function() { 
    var index = $(this).index(); 
    console.log(index) 
    console.log($("span[id^=checkboxConfirm]").eq(index)) 
    if ($(this).is(':checked')) { 
     $("span[id^=checkboxConfirm]").eq(index).html($(this).attr("name")); 
    } else { 
     $("span[id^=checkboxConfirm]").eq(index).html(''); 
    } 


}) 

+0

非常感謝。大! –