【问题标题】:What is the best ways to get the multiple checkbox checked value using JQuery使用 JQuery 获取多个复选框选中值的最佳方法是什么
【发布时间】:2014-01-08 20:14:23
【问题描述】:
<div class="myBox">
    <input type = "checkbox" id = "Banana" value = "Banana" />
    <input type = "checkbox" id = "Orange" value = "Orange" />
    <input type = "checkbox" id = "Apple" value = "Apple" />
    <input type = "checkbox" id = "Papaya" value = "Papaya" />
    <input type = "checkbox" id = "Watermelon" value = "Watermelon" />
    <input type = "checkbox" id = "Grape" value = "Grape" />
</div>

<div id="display">
</div>

如何将其存储到数组中,并在有人选中复选框时立即将所有复选框选中的值显示到“#display”div中,并在某人未选中复选框时删除该值。例如,当我单击 Banana 时,“#display” div 将显示 Banana,然后我继续单击 Grape,它将显示 Banana, Grape。取消选中复选框时,从“#display”div 中删除单词“Banana”,这样“#display”div 将只显示“Grape”。在 Jquery 中。

任何帮助将不胜感激。

【问题讨论】:

    标签: jquery html checkbox


    【解决方案1】:

    使用map() 函数获取检查值...并使用join(), 加入数组。

    试试这个

    $('.myBox  input:checkbox').change(function(){
      var tempValue='';
      tempValue=$('.myBox  input:checkbox').map(function(n){
          if(this.checked){
                return  this.value;
              };
       }).get().join(',');
    
       $('#display').html(tempValue);
    })
    

    简单的方法

     $('.myBox  input:checkbox').change(function(){
      var tempValue='';
    tempValue=$('.myBox  input:checkbox:checked').map(function(n){  //map all the checked value to tempValue with `,` seperated
                return  this.value;
       }).get().join(',');
    
       $('#display').html(tempValue);
    })
    

    fiddle here

    【讨论】:

      【解决方案2】:

      你需要这样的东西:

      $(".myBox").on("change", "[type=checkbox]", function () {
          var s = "";
          $(".myBox [type=checkbox]:checked").each(function () {
              s += this.value + ",";
          });
          $("#display").html(s.slice(0, s.length -1));
      });
      

      每当文本框中出现change 时,each 事件就会获取checked 复选框的值并将它们添加到div

      演示:http://jsfiddle.net/hungerpain/cqZcX/

      【讨论】:

        【解决方案3】:
        $(".myBox").on("change", "[type=checkbox]", function () {
            var s = "";
            $(".myBox [type=checkbox]:checked").each(function () {
                s += (s == '') ? this.value : "," + this.value;
            });
            $("#display").html(s);
        });
        

        【讨论】:

          猜你喜欢
          • 2013-11-14
          • 1970-01-01
          • 2013-12-03
          • 2010-10-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多