我有一个复选框列表:

<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />

我可以收集所有选中复选框的值;我的问题是如何获得未选中复选框的所有值?我试着:

$("input:unchecked").val();

来获得一个未选中的复选框的值,但我得到:

语法错误,无法识别的表达式:未选中。

有人能解释一下这个问题吗? 谢谢你!


当前回答

$("input:checkbox:not(:checked)")将为您提供未选中的复选框。

其他回答

要按类别选择,您可以这样做:

$("input.className:checkbox:not(:checked)")

你可以这样用:

$(":checkbox:not(:checked)")

也可以用纯js以这样的方式实现:

var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if (this.name != "chkAll") { 
      a = this.name + "|off"; 
   } 
   return a; 
}).get().join();

这将检索所有未选中的复选框,并排除“chkAll”复选框,我用来检查|取消所有复选框。因为我想知道我传递给数据库的值是什么,所以我把这些设置为off,因为复选框给了我一个on的值。

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

$("input:checkbox:not(:checked)")将为您提供未选中的复选框。