Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - Difference between "change" and "input" event for an `input` element

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 or when pressing return (Enter) and the value has been changed. 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("
On input. | " + this.tagName + " | " + this.value);
}).on("change", function () {
    $("pre").prepend("
On change | " + this.tagName + " | " + this.value);
}).on("focus", function () {
    $("pre").prepend("
On focus | " + this.tagName + " | " + this.value);
}).on("blur", function () {
    $("pre").prepend("
On blur | " + this.tagName + " | " + this.value);
});
<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...