尝试获取具有类“testclass”的所有复选框以检查它们是否被选中,如果是,则将它们的值添加到theString。获得所有复选框的值为一个类
$('.testclass').each(function() {
if (this.checked) {
var x = this.val();
theString += x + ";";
}
});
它似乎陷入了获得val的部分?
尝试获取具有类“testclass”的所有复选框以检查它们是否被选中,如果是,则将它们的值添加到theString。获得所有复选框的值为一个类
$('.testclass').each(function() {
if (this.checked) {
var x = this.val();
theString += x + ";";
}
});
它似乎陷入了获得val的部分?
尝试
$('.testclass:checked').each(function() {
alert(($(this).value))
});
因为这会提醒未定义,它不会回答问题。 – epascarello
您的问题
的问题与您的代码是this
是DOM元素,而不是一个jQuery对象。你需要改变
var x = this.val();
到
var x = this.value;
//or
var x = $(this).value; //slower
更好的解决方案
您可以使用:checked
在你的选择来获取在复选框的选中状态。您可以使用map()
来获取值。
var values = $(".testclass:checked") //get the checked checkboxes
.map(function() { //Map loops through each element in the jQuery object produces a new jQuery object containing the return values.
return this.value;
})
.get() //gets the newly created array
.join(","); //joins the array with commas as a seperator
使用$.map
试试这个
var theString=$('.testclass:checked').map(function(n){
return this.value;
}).get().join(','); //get the checked value and join it with ,
alert(theString);
theString将所有的检查值commaseperated ...
var theString = "":
$('.testclass').each(function() {
if ($(this).checked) {
theString += $(this).val()+";";
}
});
UPDATE:我不好,错过了问题的一部分,你也需要价值。
这与读取值有什么关系! – epascarello
@epascarello仔细阅读:我们正在谈论CHECKBOXES。阅读他们的价值观是无用的。你需要他们的状态。 –
哪一个.checked会告诉你它是否被选中,你仍然可以读取它们的值并且收集那些像OP所要检查的值。你改变OP的要求! – epascarello
试试下面的代码得到所有选中的复选框值
$('.testclass:checked').each(function() {
var x = this.val();
theString += x + ";";
});
仍然行不通!谁upvoted谁错过了错误! – epascarello
您可以使用:checked
与.testclass
类来获得与特定的类为选中的元素:
$('.testclass:checked').each(function() {
console.log(this.value)
});
刚刚看到的代码,它似乎你的问题是这样的:
this.val();
try c挂任本:
this.value
或
$(this).val(); //<---------jQuery version
请看看http://jsfiddle.net/2dJAN/54/
$('.check').on("click",function(){
$.each($('.testclass'), function(){
if($(this).is(':checked')){
alert($(this).val());
}
});
});
尝试
var values = $('.testclass:checked').map(function(idx, el) {
return $(el).val()
}).get();
不使用jQuery:
checkedList = [].slice.call (document.querySelectorAll ('.testclass:checked'))
.map (function (el) { return el.value; })
.join (';');
你必须希望浏览器支持,querySelector和map。 ;) – epascarello
同意,但所有流行的当前浏览器都这样做。除非使用polyfill,否则请参阅http://caniuse.com/#search=querySelector – HBP
使用[IE8](http://kangax.github.io/es5-compat-table/#Array.prototype.map)映射失败。 EOL很快! WOHOOO – epascarello
尝试:看看的CSS:检查选择,比如“.testclass:检查”,那么请在。每。 – Chris