JS可以告诉我选中或取消选中复选框吗?

时间:2018-06-06 19:51:12

标签: javascript

如何修改以下JS,告诉我复选框是选中还是取消选中?



function toggleOption(x)
{
  if (???)
      alert("Checkbox with number " + x + " was checked");
  else
      alert("Checkbox with number " + x + " was UNchecked");
}

<input type="checkbox" onclick="toggleOption(1)">
&#13;
&#13;
&#13;

为了澄清我需要检查用户是否单击复选框选中复选框,或取消选中。我不需要使用JavaScript检查或取消选中该框(用户将执行该部分)

1 个答案:

答案 0 :(得分:1)

输入具有checked属性,您可以检查该属性以了解复选框的状态

function toggleOption(x)
{
  var checked = document.querySelector("input").checked;
  if (checked)
      alert("Checkbox with number " + x + " was checked");
  else
      alert("Checkbox with number " + x + " was UNchecked");
}
<input type="checkbox" onclick="toggleOption(1)">