问题
I am having some difficulties when trying to iterate all checkbox and check if it is checked. Here is the code:
content = "<table class=\"filter-table\">";
content += "<tr><td><input class=\"pssLabel\" type=\"checkbox\" onclick=\"toggleOverlayer('pssLabel')\">Show Label</td></tr>" +
"<tr><td><div id=\"pss\"></div></td></tr>";
content += "<tr><td colspan=\"2\" style=\"padding:5px;font-size:15px;color:black;\">Development Type</td></tr>";
content += "<tr><td><input value='Commercial and Residential' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()' >Commercial and Residential</td><td><input value='Commercial' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()' >Commercial</td></tr>";
content += "<tr><td><input value='Heavy Vehicle Park' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()'>Heavy Vehicle Park</td><td><input value='Hospital' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()'>Hospital</td></tr>";
content += "<tr><td><input value='Hotel' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()'>Hotel</td><td><input value='Industrial' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()'>Industrial</td></tr>";
content += "<tr><td><input value='Industrial-White' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()'>Industrial-White</td><td><input value='Office' class=\"pssCheckBox\" type=\"checkbox\" onclick='queryPSS()'>Office</td></tr>";
Here is how I iterate all checkbox and perform checking:
function queryPSS() {
var type_filter = new Array();
//Iterate thru all checkbox
$(":checkbox").each(function(index, element) {
if($(this).is(':checked'))
{
type_filter.push($(this).val());
}
});
}
However, is there any way for me to skip the first checkbox (no matter checked or not) and check for other checkbox and store into array.
Thanks in advance.
回答1:
Since you assigned pssLabel class to your first input, you can skip the check box with that class:
$(":checkbox").each(function(index, element) {
if($(this).hasClass('pssLabel')) return;
if($(this).is(':checked'))
{
type_filter.push($(this).val());
}
});
回答2:
Just add a simple if condition like
if (index !== 0)
full code:
$("input:checkbox").each(function(index, element) {
if (index !== 0) { //skip first checkbox
if($(this).is(':checked')) {
type_filter.push($(this).val());
}
}
});
回答3:
You can use :gt(0)
$(":checkbox:gt(0)").each(function(index, element) {
--->
https://api.jquery.com/gt-selector/
回答4:
You can target only the checkboxes with class pssCheckBox
as first one don't have it.
function queryPSS() {
var type_filter = $("input.pssCheckBox:checked").map(function (index, element) {
return this.value;
}).get();
}
Also have a look at the use .map()
来源:https://stackoverflow.com/questions/22653072/iterate-all-checkbox-in-javascript