2013-06-04 15 views
0

尝试获取具有类“testclass”的所有复选框以检查它们是否被选中,如果是,则将它们的值添加到theString。获得所有复选框的值为一个类

$('.testclass').each(function() { 

     if (this.checked) { 

      var x = this.val(); 

      theString += x + ";"; 

     } 

    }); 

它似乎陷入了获得val的部分?

+0

尝试:看看的CSS:检查选择,比如“.testclass:检查”,那么请在。每。 – Chris

回答

-1

尝试

$('.testclass:checked').each(function() { 
     alert(($(this).value)) 
    }); 
+0

因为这会提醒未定义,它不会回答问题。 – epascarello

1

您的问题

的问题与您的代码是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 
0

使用$.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 ...

-1
var theString = "": 

$('.testclass').each(function() { 

     if ($(this).checked) { 

      theString += $(this).val()+";"; 

     }  

    }); 

UPDATE:我不好,错过了问题的一部分,你也需要价值。

+0

这与读取值有什么关系! – epascarello

+0

@epascarello仔细阅读:我们正在谈论CHECKBOXES。阅读他们的价值观是无用的。你需要他们的状态。 –

+0

哪一个.checked会告诉你它是否被选中,你仍然可以读取它们的值并且收集那些像OP所要检查的值。你改变OP的要求! – epascarello

0

试试下面的代码得到所有选中的复选框值

$('.testclass:checked').each(function() { 

      var x = this.val(); 

      theString += x + ";"; 

    }); 
+0

仍然行不通!谁upvoted谁错过了错误! – epascarello

1

您可以使用:checked.testclass类来获得与特定的类为选中的元素:

$('.testclass:checked').each(function() { 
    console.log(this.value) 
}); 

刚刚看到的代码,它似乎你的问题是这样的:

this.val(); 

try c挂任本:

this.value 

$(this).val(); //<---------jQuery version 
-1

请看看http://jsfiddle.net/2dJAN/54/

$('.check').on("click",function(){ 
    $.each($('.testclass'), function(){ 
     if($(this).is(':checked')){ 
      alert($(this).val()); 
     } 
    }); 
}); 
+0

哈哈..多重检查!!!!! P.S我没有downvoted –

+0

@downvoter ..请留下评论!!! –

+0

我可否知道投稿的原因? – vinothini

0

尝试

var values = $('.testclass:checked').map(function(idx, el) { 
    return $(el).val() 
}).get(); 
0

不使用jQuery:

checkedList = [].slice.call (document.querySelectorAll ('.testclass:checked')) 
         .map (function (el) { return el.value; }) 
         .join (';'); 

演示在http://jsfiddle.net/jstoolsmith/AeXWs/

+0

你必须希望浏览器支持,querySelector和map。 ;) – epascarello

+0

同意,但所有流行的当前浏览器都这样做。除非使用polyfill,否则请参阅http://caniuse.com/#search=querySelector – HBP

+0

使用[IE8](http://kangax.github.io/es5-compat-table/#Array.prototype.map)映射失败。 EOL很快! WOHOOO – epascarello

相关问题