A trigger button by pressing the Enter key in a text field skips its value

I have

Html:

<form action="" method="post" id="contactForm"> <input id='inputbox' name="inputbox" type="text" /> <button type="button" id='search'> search </button> </form> 

Javascript

 $(document).ready(function() { $("#inputbox").keyup(function(event){ if(event.keyCode == 13){ $("#search").click(); } }); $('#search').click(function(){ var inputbox= $("#inputbox").val(); //stuff }); }); 

the input value does not mean anything when I press the enter button, however, if I press the button, it works fine with the same input value

perhaps creating input global?

+4
source share
1 answer

The problem is that the default input key submits your form, even without a submit button. Therefore, you should block sending by changing the binding of the event to keypress and using event.preventDefault() , for example:

 $("#inputbox").keypress(function(event){ if(event.keyCode == 13){ event.preventDefault(); $("#search").click(); } }); 

Alternatively, you can use .submit() to run your function, change the input type to send, and avoid separate processing of keys and clicks.

HTML:

 <form action="" method="post" id="contactForm"> <input id='inputbox' name="inputbox" type="text" /> <input type="submit" value="Search"> </form> 

JavaScript:

 $(document).ready(function() { $("#contactForm").submit(submitSearch); }); function submitSearch(event) { event.preventDefault(); //do other stuff alert($("#inputbox").val()); } 
+9
source

All Articles