jQuery - ?keypress() in jQuery
keypress() in jQuery
What it does
keypress() fires when the user presses a key on the keyboard inside an input or textarea.
Syntax
$("input").keypress(function(e){
// code here
});
Example
<input type="text" id="name">
<script>
$("#name").keypress(function(){
console.log("Key pressed");
});
</script>
Key points
-
Triggered immediately on key press
-
Works only for keyboard actions
-
Does not detect mouse paste or autofill
-
Best for live typing detection
2️⃣ change() in jQuery
What it does
change() fires when the value of an element changes AND loses focus.
Syntax
$("input").change(function(){
// code here
});
Example
<input type="text" id="email">
<script>
$("#email").change(function(){
alert("Value changed!");
});
</script>
Key points
-
Fires after value is changed
-
Triggered on blur (focus out) for text inputs
-
Fires immediately for:
-
Dropdown (
select) -
Checkbox / radio
-
-
Detects paste, autofill, mouse input
3️⃣ Key differences (IMPORTANT)
| Feature | keypress() |
change() |
|---|---|---|
| Trigger time | On key press | After value change |
| Requires blur | ❌ No | ✅ Yes (text input) |
| Detects paste | ❌ No | ✅ Yes |
| Works with select | ❌ No | ✅ Yes |
| Best for | Live typing | Validation after input |
4️⃣ Real-world examples
Live character counter (keypress)
$("#msg").keypress(function(){
$("#count").text(this.value.length + 1);
});
Email validation (change)
$("#email").change(function(){
if(!this.value.includes("@")){
alert("Invalid email");
}
});
5️⃣ Interview tips
-
keypress()is deprecated in modern JS (useinputinstead) -
change()is more reliable for forms -
Use
change()for final validation -
Use
keypress()for real-time effects
6️⃣ Modern alternative (recommended)
$("input").on("input", function(){
console.log("Value changed instantly");
});