jQuery keypress() Event

jQuery keypress event triggers when a key is pressed down on the selected element. This event is similar to keydown event. The only difference is that keypress limits to some keys, like it does not work in ALT, CTRL.

Syntax of Keypress Event

$(selector).keypress(function) 

The selector is the element on which keypress event trigger. The function is an optional parameter. This function is called when user presses a key on the keyboard.

Example

<form>
<input type="text" value="Press Enter Key" id="keyprs" />
</form>	

<script>
$(document).ready(function(){  
$("#keyprs").keypress(function(){  
alert("The keypress event occurs.");  
});  
});  
</script>

Output of the above code

In the above example, an alert message is displayed when the key is pressed on the input box.


Example

<form>
\<textarea id="keyprstxt" ></textarea>
</form>	

<script>
$(document).ready(function(){  
$("#keyprstxt").keypress(function(){  
$("#keyprstxt").css("background", "yellow");  
}); 
});  
</script>

Output of the above code

In the above example, the background color of the input box is changed when the key is pressed on the textarea.



Read more articles


General Knowledge



Learn Popular Language