$("#btn").click(function() {
var vals = [];
$("body").find('input[name^=tc]:checked').each(function(e){
console.log(e + $(this).val());
vals.push($(this).val());
});
alert(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1<input type="checkbox" name="tc0" value="Y">
<br />
2<input type="checkbox" name="tc1" value="Y">
<input type="checkbox" name="tc1" value="N">
<br />
3<input type="checkbox" name="tc2" value="Y">
<input type="checkbox" name="tc2" value="N">
<br />
<button id="btn">click</button>
如果我检查 tc0 为 Y,tc1 为 Y,tc2 为 Y,然后单击按钮,我将得到 Y,Y,Y。
如果我对 tc0 检查 Y,对 tc1 不检查任何内容,对 tc2 检查 N,然后单击按钮,我会得到 Y、N,会怎么样。
我除了得到 Y,"",N。
我怎样才能做到这一点?
最佳答案
您可以遍历所有复选框
$("#btn").click(function() {
var tmp = {};
var vals = $('input[name^=tc]').map(function(e) {
var checked = $('input[name="' + this.name + '"]:checked');
if (!tmp[this.name]) {
tmp[this.name] = true;
if (checked.length > 1) {
return [checked.map(function() {
return this.value;
}).get()];
} else {
return checked.val() || '';
}
};
}).get();
snippet.log(JSON.stringify(vals));
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1
<input type="checkbox" name="tc0" value="Y">
<br />2
<input type="checkbox" name="tc1" value="Y">
<input type="checkbox" name="tc1" value="N">
<br />3
<input type="checkbox" name="tc2" value="Y">
<input type="checkbox" name="tc2" value="N">
<br />
<button id="btn">click</button>
关于javascript - 如何根据同名属性获取每个复选框状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641230/