【问题标题】:use jQuery to get values of selected checkboxes使用 jQuery 获取选中复选框的值
【发布时间】:2012-07-02 19:32:56
【问题描述】:

我想遍历复选框组“locationthemes”并构建一个包含所有选定值的字符串。 因此,选择复选框2和4时,结果将是:“3,8”

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

我在这里检查过:http://api.jquery.com/checked-selector/ 但没有示例如何按名称选择复选框组。

我该怎么做?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    在 jQuery 中只需使用类似的属性选择器

    $('input[name="locationthemes"]:checked');
    

    选择名称为“locationthemes”的所有选中输入

    console.log($('input[name="locationthemes"]:checked').serialize());
    
    //or
    
    $('input[name="locationthemes"]:checked').each(function() {
       console.log(this.value);
    });
    

    Demo


    VanillaJS

    [].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
       console.log(cb.value); 
    });
    

    Demo


    在 ES6/扩展运算符中

    [...document.querySelectorAll('input[name="locationthemes"]:checked')]
       .forEach((cb) => console.log(cb.value));
    

    Demo

    【讨论】:

    • 你,我的朋友,是个救命稻草。
    • 我特别喜欢使用控制台日志的想法。谢谢你。
    【解决方案2】:
    $('input:checkbox[name=locationthemes]:checked').each(function() 
    {
       // add $(this).val() to your array
    });
    

    工作Demo

    使用jQuery的is()函数:

    $('input:checkbox[name=locationthemes]').each(function() 
    {    
        if($(this).is(':checked'))
          alert($(this).val());
    });
    

    【讨论】:

      【解决方案3】:

      映射数组是最快最干净的。

      var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })
      

      将值作为数组返回,例如:

      array => [2,3]
      

      假设城堡和谷仓被检查,而其他没有。

      【讨论】:

        【解决方案4】:

        $("#locationthemes").prop("checked")

        【讨论】:

        • 这应该是一条评论
        【解决方案5】:

        使用jquery的map函数

        var checkboxValues = [];
        $('input[name=checkboxName]:checked').map(function() {
                    checkboxValues.push($(this).val());
        });
        

        【讨论】:

        • 在这个例子中checkboxName应该是“locationthemes”
        【解决方案6】:
        You can also use the below code
        $("input:checkbox:checked").map(function()
        {
        return $(this).val();
        }).get();
        

        【讨论】:

        • 如何将此结果赋值给变量
        【解决方案7】:

        更现代的方法:

        const selectedValues = $('input[name="locationthemes"]:checked').map( function () { 
                return $(this).val(); 
            })
            .get()
            .join(', ');
        

        我们首先找到所有具有给定名称的选中复选框,然后 jQuery 的 map() 遍历它们中的每一个,调用它的回调以获取值,并将结果作为一个新的 jQuery 集合返回,该集合现在包含复选框值。然后我们调用 get() 来获取一个值数组,然后 join() 将它们连接成一个字符串 - 然后将其分配给常量 selectedValues。

        【讨论】:

          【解决方案8】:
          var SlectedList = new Array();
          $("input.yorcheckboxclass:checked").each(function() {
               SlectedList.push($(this).val());
          });
          

          【讨论】:

          • 请在您的回答中提供解释。
          【解决方案9】:

          所以都在一行中:

          var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");
          

          ..关于选择器 [id*="checkbox"] 的注释,它将抓取其中包含字符串“checkbox”的任何项目。这里有点笨拙,但如果您试图从 .NET CheckBoxList 之类的东西中提取选定的值,那就太好了。在这种情况下,“复选框”将是您为 CheckBoxList 控件指定的名称。

          【讨论】:

          • 这很有用@mike
          【解决方案10】:

          Source - More Detail

          使用 jQuery 获取选中的复选框值

          然后我们编写 jQuery 脚本来使用 jQuery each() 在数组中获取选中的复选框值。使用这个 jQuery 函数,它运行一个循环来获取检查的值并将其放入一个数组中。

          <!DOCTYPE html>
              <html lang="en">
              <head>
              <meta charset="utf-8">
              <title>Get Selected Checkboxes Value Using jQuery</title>
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
              <script type="text/javascript">
                  $(document).ready(function() {
                      $(".btn").click(function() {
                          var locationthemes = [];
                          $.each($("input[name='locationthemes']:checked"), function() {
                              locationthemes.push($(this).val());
                          });
                          alert("My location themes colors are: " + locationthemes.join(", "));
                      });
                  });
              </script>
              </head>
              <body>
                  <form method="POST">
                  <h3>Select your location themes:</h3>
                  <input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
                  <label for="checkbox-1">Castle</label>
                  <input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
                  <label for="checkbox-2">Barn</label>
                  <input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
                  <label for="checkbox-3">Restaurant</label>
                  <input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
                  <label for="checkbox-4">Bar</label>
                  <br>
                  <button type="button" class="btn">Get Values</button>
              </form>
              </body>
              </html>
          

          【讨论】:

            【解决方案11】:
            var voyageId = new Array(); 
            $("input[name='voyageId[]']:checked:enabled").each(function () {
               voyageId.push($(this).val());
            });      
            

            【讨论】:

            • 升级:var voyageIds = $('input[name="voyageId[]"]:checked:enabled').map(function() {return this.value; }).get();
            【解决方案12】:

            Jquery 3.3.1,在按钮点击时获取所有选中复选框的值

            $(document).ready(function(){
             $(".btn-submit").click(function(){
              $('.cbCheck:checkbox:checked').each(function(){
            	alert($(this).val())
              });
             });			
            });
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">
              <label for="vehicle1"> I have a bike</label><br>
              <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">
              <label for="vehicle2"> I have a car</label><br>
              <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">
              <label for="vehicle3"> I have a boat</label><br><br>
              <input type="submit" value="Submit" class="btn-submit">

            【讨论】:

              猜你喜欢
              • 2018-08-25
              • 2012-12-20
              • 1970-01-01
              • 2013-06-07
              • 2015-10-30
              • 1970-01-01
              • 2011-02-19
              • 1970-01-01
              • 2010-11-20
              相关资源
              最近更新 更多