I have a textbox in which i written keypress function for the Enter Key, which should show alert.
Here is my html and script.
Here is my Textbox :
<li>
<input type="text" class="fi_top" placeholder="Howdy" id="howdy" value="">
</li>
And inside the page i have
Script :
$( "#howdy" ).keypress(function( event )
{
if ( event.which == 13 ) {
alert('okay');
}
});
But i am not getting alert while i press enter at the textbox.
What is the mistake i am doing and how can i fix this ?
I have a textbox in which i written keypress function for the Enter Key, which should show alert.
Here is my html and script.
Here is my Textbox :
<li>
<input type="text" class="fi_top" placeholder="Howdy" id="howdy" value="">
</li>
And inside the page i have
Script :
$( "#howdy" ).keypress(function( event )
{
if ( event.which == 13 ) {
alert('okay');
}
});
But i am not getting alert while i press enter at the textbox.
What is the mistake i am doing and how can i fix this ?
Share Improve this question asked Nov 24, 2014 at 7:19 ABDABD 8892 gold badges13 silver badges29 bronze badges 6- try using event.keyCode == 13 – VSri58 Commented Nov 24, 2014 at 7:20
- I tried just now that tooo.. But not working :( – ABD Commented Nov 24, 2014 at 7:22
- keyCode with C in caps. See my answer. – VSri58 Commented Nov 24, 2014 at 7:25
- are you adding the element in runtime or is it loaded with the page content – Manish Jangir Commented Nov 24, 2014 at 7:25
- You code is working, have you included the jquery library to your page. here is working fiddle by your code jsfiddle/v3fggs1w – Vinay Pratap Singh Bhadauria Commented Nov 24, 2014 at 7:29
4 Answers
Reset to default 12I think you are adding this element dynamically in the HTML and .keypress will only work on pre loaded elements. jQuery has provided $(document).on for dynamically added elements.
$(document).on("keypress", "#howdy", function (e) {
if (e.keyCode == 13 || e.which == '13') {
//Do your work
}
});
Hey you should try keypress
event like this
$("#howdy").keypress(function() {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
callAjaxGetJoiningDate($(this).val());
event.preventDefault()
}
});
Try
event.KeyCode == 13
JS Code:
$( "#howdy" ).keypress(function( event )
{
if ( event.keyCode == 13 ) {
alert('okay');
}
});
See this fiddle
Place this in document.ready block, so that it will trigger after whole dom will load. Eventually mark your script with defer attribute.
You should use both which and keyCode , bacause they don't work on all browsers.
$( "#howdy" ).keypress(function( event )
{
if ( event.which == 13 || event.keyCode == 13) {
alert('okay');
}
});