17

我有几个带有名称数组的复选框,我希望复选框的输出是一个带有逗号分隔列表的变量。

<input type="checkbox" name="example[]" value="288" />
<input type="checkbox" name="example[]" value="289" />
<input type="checkbox" name="example[]" value="290" />

例如,如果选择了第一个和最后一个框,则输出将是:

var output = "288,290";

我怎么能用 jQuery 做到这一点?

4

4 回答 4

32

You can use :checkbox and name attribute selector (:checkbox[name=example\\[\\]]) to get the list of checkbox with name="example[]" and then you can use :checked filter to get only the selected checkbox.

Then you can use .map function to create an array out of the selected checkbox.

DEMO

var output = $.map($(':checkbox[name=example\\[\\]]:checked'), function(n, i){
      return n.value;
}).join(',');
于 2012-03-06T22:59:52.737 回答
12

目前未经测试,但我相信以下应该有效:

var valuesArray = $('input:checkbox:checked').map( function () {
    return $(this).val();
}).get().join();

稍作休息后,编辑为使用本机 DOM,而不是$(this).val()(在上下文中这是不必要的昂贵):

var valuesArray = $('input:checkbox:checked').map( function() {
    return this.value;
}).get().join(",");
于 2012-03-06T22:57:08.770 回答
5

jQuery 如何获取多个复选框的值并输出为逗号分隔的字符串列表。

https://www.tutsmake.com/jquery-multiple-checkbox-values-to-comma-separated-string/

    $(document).ready(function() {
        $(".btn_click").click(function(){
 
            var programming = $("input[name='programming']:checked").map(function() {
                return this.value;
            }).get().join(', ');
 
            alert("My favourite programming languages are: " + programming);
        });
    });
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Values of Selected Checboxes</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
    <form>
        <h3>Select your favorite Programming Languages :</h3>
        <label><input type="checkbox" value="PHP" name="programming"> PHP</label>
        <label><input type="checkbox" value="Java" name="programming"> Java</label>
        <label><input type="checkbox" value="Ruby" name="programming"> Ruby</label>
        <label><input type="checkbox" value="Python" name="programming"> Python</label>
        <label><input type="checkbox" value="JavaScript" name="programming"> JavaScript</label>
        <label><input type="checkbox" value="Rust" name="programming">Rust</label>
        <label><input type="checkbox" value="C" name="programming"> C</label>
        <br>
        <button type="button" class="btn_click" style="margin-top: 10px;">Click here to Get Values</button>
    </form>
</body>
</html>  

于 2019-04-20T09:51:47.953 回答
4
var valuesArray = $('input[name="valuehere"]:checked').map(function () {  
        return this.value;
        }).get().join(",");

总是为我工作

于 2014-06-03T11:27:52.010 回答