-1

How can I modify the following JS to where it will tell me whether the checkbox was checked or unchecked?

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)">

To clarify I need to check if user clicking the checkbox made the checkbox checked, or unchecked. I don't need to check or uncheck the box using JavaScript (the user will be doing that part)

Dennis
  • 7,907
  • 11
  • 65
  • 115
  • 2
    Possible duplicate of [Check/Uncheck checkbox with JavaScript?](https://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript) – Surreal Jun 06 '18 at 19:56
  • The user will check/uncheck the box, I need the JS to detect whether user has checked or unchecked the box. – Dennis Jun 06 '18 at 20:09
  • Your onclick then should handle it, if its hitting your toggleOption method, the user has checked or unchecked the box – Surreal Jun 06 '18 at 20:50

1 Answers1

1

input has a checked property that you can check to know the status of checkbox

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)">
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
  • If there's an option `1` the chances are really high that there will also be an option `2` and `3` and `4` and ... – Andreas Jun 06 '18 at 19:53
  • Why would you query for an input (which would most likely not be the same checkbox) inside the listener? Why not use `this`? – chazsolo Jun 06 '18 at 19:54