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
}

推荐答案

我使用的一种可靠方法是:

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.

See Properties and Attributes in HTML

Jquery相关问答推荐

当一个很长的活动增加标题时,满历js每周都会出现.这是一种让标题只出现一次的方法吗?

使用jquery ui来回滑动切换

如何用each替换元素的attr href

如何定位 prism.js 脚本中包含的代码?

jQuery .first() 方法返回第一个元素的集合

jQuery 时间 Select 器

如何从 jQuery 转到 React.js?

jQuery javascript 正则表达式 将
替换为 \n

如何在单击时 Select 多选 Select 框的所有选项?

JavaScript 吸管(告诉鼠标光标下像素的 colored颜色 )

jQuery UI 滑块(以编程方式设置)

使用 JavaScript 和 jQuery,跨浏览器处理按键事件 (F1-F12)

jQuery计算所有文本字段中的值的总和

如何获取 onclick 调用对象?

动画元素变换旋转

未捕获的 TypeError:data.push 不是函数

$(document).on("click"... 不工作?

使用 jQuery Select 空文本输入

如何在没有鼠标事件的情况下在 jQuery 中获取鼠标位置?

如何获取 jQuery 下拉值 onchange 事件