I'm having trouble figuring this out. I have two checkboxes (in the future will have more):
checkSurfaceEnvironment-1
checkSurfaceEnvironment-2
Basically, I want to write an if statement and test if one of them is checked and another is NOT checked. What's the easiest way to accomplish the following:
if ( $("#checkSurfaceEnvironment-1").attr('checked', true) &&
$("#checkSurfaceEnvironment-2").is('**(NOT??)** :checked') ) {
// do something
}
ベストアンサー1
One reliable way I use is:
if($("#checkSurfaceEnvironment-1").prop('checked') == true){
//do something
}
If you want to iterate over checked elements use the parent element
$("#parentId").find("checkbox").each(function(){
if ($(this).prop('checked')==true){
//do something
}
});
More info:
This works well because all checkboxes have a property checked which stores the actual state of the checkbox. If you wish you can inspect the page and try to check and uncheck a checkbox, and you will notice the attribute "checked" (if present) will remain the same. This attribute only represents the initial state of the checkbox, and not the current state. The current state is stored in the property checked of the dom element for that checkbox.