Difference between “change” and “input” event for

2019-01-05 08:35发布

Can someone tell me what the difference between the change and input events is?

I am using jQuery for adding them:

$('input[type="text"]').on('change', function() {
    alert($(this).val());
})

It also works with input instead of change.

Maybe some difference in the event ordering relative to focus?

2条回答
神经病院院长
2楼-- · 2019-01-05 09:06

According to this post:

  • oninput event occurs when the text content of an element is changed through the user interface.

  • onchange occurs when the selection, the checked state or the contents of an element have changed. In some cases, it only occurs when the element loses the focus. The onchange attribute can be used with: <input>, <select>, and <textarea>.

TL;DR:

  • oninput: any change made in the text content
  • onchange:
    • If it is an <input />: change + lose focus
    • If it is a <select>: change option

$("input, select").on("input", function () {
    $("pre").prepend("\nOn input. | " + this.tagName);
}).on("change", function () {
    $("pre").prepend("\nOn change | " + this.tagName);
}).on("focus", function () {
    $("pre").prepend("\nOn focus | " + this.tagName);
}).on("blur", function () {
    $("pre").prepend("\nOn blur | " + this.tagName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<select>
  <option>Alice</option>
  <option>Bob</option>
  <option>Carol</option>
  <option>Dave</option>
  <option>Emma</option>
</select>
<pre></pre>

查看更多
趁早两清
3楼-- · 2019-01-05 09:08
  • The change event fires in most browsers when content is changed and the element loses focus, basically an aggregate of changes. You will not see this fired for every single changed unlike the input event.

  • The input event fires synchronously on change of the content for the element. So you will see this event occur more often. Browser support varies.

查看更多
登录 后发表回答