How to Detect Change in a Text Input Box in jQuery
Topic: JavaScript / jQueryPrev|Next
Answer: Use the input
Event
You can bind the input
event to an input text box using on()
method to detect any change in it.
The following example will display the entered value when you type something inside the input field.
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Detect Change in Input Field</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#myInput").on("input", function(){
// Print entered value in a div box
$("#result").text($(this).val());
});
});
</script>
</head>
<body>
<p><input type="text" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
</body>
</html>
Note that the input
event fires on keyboard input, mouse drag, autofill and even copy-paste. But, it will not fire if you paste the same string or select and retype the same character, etc. inside the input.
Also, if you use the change
event here it will not work as expected, since in case of text inputs the change
event fires only when the element loses focus (i.e. onblur). Try the above example by replacing the string "input"
with "change"
(line no-8), and see how it works.
Related FAQ
Here are some more FAQ related to this topic: