perform an action on checkbox checked or unchecked event on html form

前端 未结 7 2285
遥遥无期
遥遥无期 2020-12-06 09:40

I have a checkbox on a form which is unchecked by default as usual. now I want to perform two separated actions on checked and unchecked state of this checkbox.

this

相关标签:
7条回答
  • 2020-12-06 10:04

    The problem is how you've attached the listener:

    <input type="checkbox" ...  onchange="doalert(this.id)">
    

    Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).

    Since the window object doesn't have a checked property, this.checked always resolves to false.

    If you want this within doalert to be the element, attach the listener using addEventListener:

    window.onload = function() {
      var input = document.querySelector('#g01-01');
      if (input) {   
        input.addEventListener('change', doalert, false);
      }
    }
    

    Or if you wish to use an inline listener:

    <input type="checkbox" ...  onchange="doalert.call(this, this.id)">
    
    0 讨论(0)
提交回复
热议问题