What is the difference between onBlur and onChange attribute in HTML?

前端 未结 7 1363
[愿得一人]
[愿得一人] 2020-11-29 18:18

When is one called versus the other? Is there a situation were onChange would be called but onBlur would not be called?

相关标签:
7条回答
  • 2020-11-29 18:35

    I think it's important to note here that onBlur() fires regardless.

    This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.

    onChange() will only fire when the value is changed.

    0 讨论(0)
  • 2020-11-29 18:38

    onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however.

    In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE. However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order. However, I've seen cases where IE will also fire blur first, so be careful. You can't assume that either the onblur or the onchange will happen before the other one.

    0 讨论(0)
  • 2020-11-29 18:45

    In Firefox the onchange fires only when you tab or else click outside the input field. The same is true of Onblur. The difference is that onblur will fire whether you changed anything in the field or not. It is possible that ENTER will fire one or both of these, but you wouldn't know that if you disable the ENTER in your forms to prevent unexpected submits.

    0 讨论(0)
  • 2020-11-29 18:45

    onBlur is when your focus is no longer on the field in question.

    The onblur property returns the onBlur event handler code, if any, that exists on the current element.

    onChange is when the value of the field changes.

    0 讨论(0)
  • 2020-11-29 18:47

    An example to make things concrete. If you have a selection thus:

    <select onchange="" onblur="">
      <option>....
    </select>
    

    the onblur() is called when you navigate away. The onchange() is called when you select a different option from the selection - i.e. you change what it's currently selected as.

    0 讨论(0)
  • 2020-11-29 18:54

    The onBlur event is fired when you have moved away from an object without necessarily having changed its value.

    The onChange event is only called when you have changed the value of the field and it loses focus.

    You might want to take a look at quirksmode's intro to events. This is a great place to get info on what's going on in your browser when you interact with it. His book is good too.

    0 讨论(0)
提交回复
热议问题