2014-07-26 35 views

回答

1

單擊複選框後,將複選框的值添加到字符串中,並將文本框的值更改爲字符串的值。使用each()查看複選框。

試試這個:

$(document).ready(function(){ 
    $("input:checkbox").click(function() { 
     var string = ""; 
     $("input:checked").each(function() { 
      string += $(this).val(); 
     }); 
     $("#txtbox").val(string); 
    }); 
}); 

JSFiddle Demo

0

請試試下面的代碼片段。

<!DOCTYPE html> 
<html> 
<head> 
    <title>Test</title> 
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script> 
     $(document).ready(function() { 
      $(".chk").click(function() { 
       getValueUsingClass(); 
      }); 
     }); 

     function getValueUsingClass() { 
      /* declare an checkbox array */ 
      var chkArray = []; 

      /* look for all checkboes that have a class 'chk' attached to it and check if it was checked */ 
      $(".chk:checked").each(function() { 
       chkArray.push($(this).val()); 
      }); 

      /* we join the array separated by the comma */ 
      var selected; 
      selected = chkArray.join(',') + ","; 

      /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */ 
      if (selected.length > 1) { 
       alert("You have selected " + selected); 
      } else { 
       alert("Please at least one of the checkbox"); 
      } 
     } 
    </script> 
</head> 
<body> 
    <div id="checkboxlist"> 
     <div> 
      <input type="checkbox" value="1" class="chk"> 
      Value 1 
     </div> 
     <div> 
      <input type="checkbox" value="2" class="chk"> 
      Value 2 
     </div> 
     <div> 
      <input type="checkbox" value="3" class="chk"> 
      Value 3 
     </div> 
     <div> 
      <input type="checkbox" value="4" class="chk"> 
      Value 4 
     </div> 
     <div> 
      <input type="checkbox" value="5" class="chk"> 
      Value 5 
     </div> 

    </div> 
</body> 
</html> 
0
<div id="checkboxes"> 
    <input type="checkbox" value="1" /> 
    <input type="checkbox" value="2" /> 
    <input type="checkbox" value="3" /> 
</div> 
var el = document.getElementById('checkboxes'), 
    checkEls = [].slice.call(el.children); 
el.addEventListener('change', function() { 
    var values = checkEls 
     .filter(function(checkEl){ 
      return checkEl.checked; 
     }) 
     .map(function(checkEl){ 
      return checkEl.value; 
     }); 
    /* In ES6, just use 
     var values = checkEls.filter(el => el.checked).map(el => el.value); 
    */ 
}); 

Demo

相關問題