0

Basically as title says - I'm trying to switch checkbox's checked value with an function that's being pinned to that checkbox as a onclick, and accepts this

<input type="checkbox" onclick="toggleCheckbox(this)" />

<script>
  function toggleCheckbox(e)
  {
    e.checked = !e.checked;
  }
</script>

But why the new value isnt negation of previous? its always T/F/T/F but it should be T/F/F/T/T/F/F as an console output

<input type="checkbox" onclick="toggleCheckbox(this)" />

<script>
  function toggleCheckbox(e)
  {
    console.log(e.checked)
    e.checked = !e.checked;
    console.log(e.checked)
  }
</script>
tezzly
  • 723
  • 1
  • 5
  • 12

1 Answers1

1

You dont need to set anything as by default html will will take care of the check. If you want any additional logic such as ajax, filtering you can use the e.checked and do what you want to do with it.

<input type="checkbox" id="checkbox" onclick="toggleCheckbox(this)" />

<script>
  function toggleCheckbox(e)
  {
    console.log(e.checked)
  }
</script>
Subhendu Kundu
  • 3,618
  • 6
  • 26
  • 57
  • Cannot that checkbox be sent as a param? – tezzly Mar 04 '19 at 19:42
  • Yes are already sending the param, which is accessible as `e` as thats the first and only parameter/ argument you are passing while calling the function. Learn more from https://stackoverflow.com/questions/13286233/pass-a-javascript-function-as-parameter – Subhendu Kundu Mar 04 '19 at 19:51