Trigger <button> when pressing the Enter key in text input - javascript

I'm making a search bar with the text-bar as an tag, and the search-button as a , the reason I use a instead of is because I'm using a picture of a magnifying glass on the button, an when I use it doesn't want to position itself properly.
Here is my HTML:
<form id="search-form" href="#test1" class="smoothscroll">
<input type="text" id="searchText" onClick="this.select();" placeholder="Search..."/>
<button type="button" id="searchButton">
<img src="magnify.png" id="magnify"/>
</button>
</form>
And here is the jquery:
$(document).ready(function () {
$("#searchButton").click(function () {
var text = document.getElementById('searchText').value;
$("html, body").animate({
scrollTop: ($('#' + text).offset().top)
}, 2000);
});
$("#searchText").keyup(function (event) {
if (event.keyCode == 13) {
$("#searchButton").click();
}
});
});
Thank you for helping.

As per the docs, You should use .which instead of keyCode:
$("#searchText").keyup(function(event){
if(event.which == 13){
$("#searchButton").click();
}
// Make sure the form isn't submitted
event.preventDefault();
});
To determine which key was pressed, examine the event object that is
passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the key code.

Try this
$("#searchText").keyup(function (event) {
var code= event.keyCode ? event.keyCode : event.which;
// or use simply, var code= event.keyCode || event.which;
if (code == 13) {
$("#searchButton").click();
}
});
Demo

$("#searchText").keyup(function(event){
if (event.which === 13) {
$("#searchButton").trigger("click");
}
});
also see Javascript .keyCode vs. .which?

Related

JavaScript: Pressing enter on a text input invoking a function

http://codepen.io/abdulahhamzic/pen/YqMQwB
How do I make it so that when I press enter on a text input, it calls a function? I tried using this:
<input type="text" onkeypress="clickPress()">
But the problem is I only want to press enter to call that function, not press any key. How do I achieve that?
2022 Update: onkeypress is deprecated.
You can use onKeyDown instead
What you'd want to do is check whether the event's key is the enter key:
In your html, add the event argument
<input type="text" onkeypress="clickPress(event)">
And in your handler, add an event parameter
function clickPress(event) {
if (event.keyCode == 13) {
// do something
}
}
2022 Update: event.keyCode is deprecated on many browsers.
You should do this now:
function clickPress(event) {
if (event.key == "Enter") {
// do something
}
}
Use a form instead (the submit event only runs once instead of every key press):
// Attach the event handler to the form element
document.querySelector('.js-form')?.addEventListener('submit', e => {
e.preventDefault();
alert(e.currentTarget.myText.value);
});
<form class="js-form">
<input type="text" name="myText">
</form>
The Enter button has a keyCode of 13, so you can use the keypress event using jQuery
$("input").keypress(function(event) {
if (event.which == 13) {
alert("Enter was pressed");
}
});
or, in pure javascript:
<input type="text" onkeypress="clickPress(event)">
function clickPress(event) {
if (event.keyCode == 13) {
// do something
}
}
Get the event's keycode and test if it's enter (keycode 13)
<script>
function clickPress(e){
if (event.keyCode == 13) {
// Enter was pressed
alert("enter");
}
}
</script>
<input type="text" onkeypress="clickPress(event)" />
jsfiddle
There could be several "better" ways to do what you want to do but just for the sake of simplicity, you could do this:
<input type="text" id="txt">
Instead of listening to the onkeypress you could attach an event listener within the <script></script> tags and do this:
var myText = document.getElementById("txt");
myText.addEventListener("keyup", function(e) {
if (e.which === 13) {
//The keycode for enter key is 13
alert(e.target.value);
}
});
And yeah this is definitely a duplicate question.

How to handle multiple buttons enter key functionality?

In my page there are two buttons. For enter key functionality I have written the following jQuery code.
$(function () {
$("#first-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
$("#second-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
});
But always when click on enter key first one is firing. Please tell me how to handle the multiple button enter key functionality.
Try something like this
HTML :
<label>TextBox : </label>
<input id="textbox" type="text" size="50" />
<label>TextBox 2: </label>
<input id="textbox2" type="text" size="50" />
JQuery
$('#textbox , #textbox2').keyup(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a "enter" key in textbox');
}
event.preventDefault();
}).focus();
DEMO
Some browser prefer keycode and other use which ... I suggest you to use both..
You do not need to focus on two buttons at the same time. Try doing something like this:
$("#button1").keypress(function(event){
if ( event.which == 13 ){
//Do something}
$("#button2").keypress(function(event){
if( event.which == 13 ){
//Do something else}
The problem i think is with your event.preventDefault() function which stops the propogation of the event once a function is executed. In your case, your first function might be getting completed before the second one and hence the second one gets aborted in the middle.
$("#first-button-id , #second-button-id ").keyup(function(event){
if ( event.which == 13 ) {
alert("you pressed enter.");
event.preventDefault();
}
}
The reason the first submit button is always firing is because that's the default behavior of a web page which you haven't actually altered with your code.
Try this:
$(function () {
$("#first-button-id, #second-button-id").keyup(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
if (e.keyCode == '13') {
$(this).trigger("click");
}
});
});
What you seem to be asking about strikes me as rather odd. It looks like you want second-button to be 'clicked' if the focus is on second-button and enter is pressed. Tabbing until the focus is on the correct button is really the only practical way this could happen.
Try this.
$('#first-button-id').on("keydown", function (e)
{
if (e.keyCode == 13)
{
e.preventDefault();
$("first-button-id").click();
}
});

How can I detect pressing Enter on the keyboard using jQuery?

I would like to detect whether the user has pressed Enter using jQuery.
How is this possible? Does it require a plugin?
It looks like I need to use the keypress() method.
Are there browser issues with that command - like are there any browser compatibility issues I should know about?
The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:
$(document).on('keypress',function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
I wrote a small plugin to make it easier to bind the "on enter key pressed" event:
$.fn.enterKey = function (fnc) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {
fnc.call(this, ev);
}
})
})
}
Usage:
$("#input").enterKey(function () {
alert('Enter!');
})
I couldn't get the code posted by Paolo Bergantino to work, but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed Enter!');
}
});
Link to example on JS Bin
I found this to be more cross-browser compatible:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
You can do this using the jQuery 'keydown' event handler:
$("#start").on("keydown", function(event) {
if(event.which == 13)
alert("Entered!");
});
Use event.key and modern JavaScript!
$(document).keypress(function(event) {
if (event.key === "Enter") {
// Do something
}
});
Or without jQuery:
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
// Do something better
}
});
Mozilla documentation
Supported Browsers
I came up with this solution:
$(document).ready(function(){
$('#loginforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('login pressed');
}
});
$('#signupforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('register');
}
});
});
There's a keypress() event method. The Enter key's ASCII number is 13 and is not dependent on which browser is being used.
A minor extension of Andrea's answer makes the helper method more useful when you may also want to capture modified enter presses (i.e., Ctrl + Enter or Shift + Enter). For example, this variant allows binding like:
$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')
to submit a form when the user presses Ctrl + Enter with focus on that form's textarea.
$.fn.enterKey = function (fnc, mod) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
fnc.call(this, ev);
}
})
})
}
(See also *Ctrl + Enter using jQuery in a TEXTAREA)
In some cases, you may need to suppress the ENTER key for a certain area of a page but not for other areas of a page, like the page below that contains a header <div> with a SEARCH field.
It took me a bit to figure out how to do this, and I am posting this simple yet complete example up here for the community.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Script</title>
<script src="/lib/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('.container .content input').keypress(function (event) {
if (event.keyCode == 10 || event.keyCode == 13) {
alert('Form Submission needs to occur using the Submit button.');
event.preventDefault();
}
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<div class="FileSearch">
<!-- Other HTML here -->
</div>
</div>
<div class="content">
<form id="testInput" action="#" method="post">
<input type="text" name="text1" />
<input type="text" name="text2" />
<input type="text" name="text3" />
<input type="submit" name="Submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
Link to JSFiddle Playground: The [Submit] button does not do anything, but pressing ENTER from one of the Text Box controls will not submit the form.
Try this to detect the Enter key pressed.
$(document).on("keypress", function(e){
if(e.which == 13){
alert("You've pressed the enter key!");
}
});
See demo # detect enter key press on keyboard
As the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
$(document).keydown(function(event) {
if (event.keyCode || event.which === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Call function, trigger events and everything you want to do. Example: Trigger the button element with a click
$("#btn").trigger('click');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn" onclick="console.log('Button Pressed.')">&nbsp</button>
I used $(document).on("keydown").
On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.
$(document).on("keydown", function(e) {
const ENTER_KEY_CODE = 13;
const ENTER_KEY = "Enter";
var code = e.keyCode || e.which
var key = e.key
if (code == ENTER_KEY_CODE || key == ENTER_KEY) {
console.log("Enter key pressed")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
$(document).keydown(function (event) {
//proper indentiation of keycode and which to be equal to 13.
if ( (event.keyCode || event.which) === 13) {
// Cancel the default action, if needed
event.preventDefault();
//call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
$("#btnsearch").trigger('click');
}
});
This my how I solved it. You should use return false;
$(document).on('keypress', function(e) {
if(e.which == 13) {
$('#sub_btn').trigger('click');
alert('You pressed the "Enter" key somewhere');
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
<div class="modal-header">
<button type="button" class="close" id="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Subscribe to our Technical Analysis</h4>
</div>
<div class="modal-body">
<p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
<div class="input-group">
<input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
</div>
<span id="save-error"></span>
</div>
<div class="modal-footer">
<div class="input-group-append">
<input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
</div>
</div>
</form>
I think the simplest method would be using vanilla JavaScript:
document.onkeyup = function(event) {
if (event.key === 13){
alert("Enter was pressed");
}
}
The easy way to detect whether the user has pressed Enter is to use the key number. The Enter key number is equal to 13.
To check the value of key in your device:
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// Backspace in Internet Explorer only is on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
By pressing the Enter key, you will get result as 13. Using the key value, you can call a function or do whatever you wish:
$(document).keypress(function(e) {
if(e.which == 13) {
console.log("The user pressed the Enter key");
// The code you want to run
}
});
If you want to target a button once the Enter key is pressed, you can use the code:
$(document).bind('keypress', function(e) {
if(e.which === 13) { // Return
$('#buttonname').trigger('click');
}
});
$(document).keyup(function(e) {
if(e.key === 'Enter') {
//Do the stuff
}
});
$(function(){
$('.modal-content').keypress(function(e){
debugger
var id = this.children[2].children[0].id;
if(e.which == 13) {
e.preventDefault();
$("#"+id).click();
}
})
});

Prevent form submission on Enter key press

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call my JavaScript function, but when I press it, the form is submitted.
How do I prevent the form from being submitted when the enter key is pressed?
if(characterCode == 13) {
// returning false will prevent the event from bubbling up.
return false;
} else{
return true;
}
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
NOTE:
It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.
Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.
Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.
Use both event.which and event.keyCode:
function (event) {
if (event.which == 13 || event.keyCode == 13) {
//code to execute here
return false;
}
return true;
};
event.key === "Enter"
More recent and much cleaner: use event.key. No more arbitrary number codes!
NOTE: The old properties (.keyCode and .which) are Deprecated.
const node = document.getElementsByClassName("mySelect")[0];
node.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
// Do more work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keydown", ({key}) => {
if (key === "Enter") // Handle press
})
Mozilla Docs
Supported Browsers
If you're using jQuery:
$('input[type=text]').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
Detect Enter key pressed on whole document:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
http://jsfiddle.net/umerqureshi/dcjsa08n/3/
Override the onsubmit action of the form to be a call to your function and add return false after it, ie:
<form onsubmit="javascript:myfunc();return false;" >
A react js solution
handleChange: function(e) {
if (e.key == 'Enter') {
console.log('test');
}
<div>
<Input type="text"
ref = "input"
placeholder="hiya"
onKeyPress={this.handleChange}
/>
</div>
So maybe the best solution to cover as many browsers as possible and be future proof would be
if (event.which === 13 || event.keyCode === 13 || event.key === "Enter")
Here is how you can do it using JavaScript:
//in your **popup.js** file just use this function
var input = document.getElementById("textSearch");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
alert("yes it works,I'm happy ");
}
});
<!--Let's say this is your html file-->
<!DOCTYPE html>
<html>
<body style="width: 500px">
<input placeholder="Enter the text and press enter" type="text" id="textSearch"/>
<script type="text/javascript" src="public/js/popup.js"></script>
</body>
</html>
Below code will add listener for ENTER key on entire page.
This can be very useful in screens with single Action button eg Login, Register, Submit etc.
<head>
<!--Import jQuery IMPORTANT -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!--Listen to Enter key event-->
<script type="text/javascript">
$(document).keypress(function (e) {
if (e.which == 13 || event.keyCode == 13) {
alert('enter key is pressed');
}
});
</script>
</head>
Tested on all browsers.
A jQuery solution.
I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.
$(selector).keyup(function(e){
/*
* Delay the enter key form submit till after the hidden
* input is updated.
*/
// No need to do anything if it's not the enter key
// Also only e.which is needed as this is the jQuery event object.
if (e.which !== 13) {
return;
}
// Prevent form submit
e.preventDefault();
// Trigger the blur event.
this.blur();
// Submit the form.
$(e.target).closest('form').submit();
});
Would be nice to get a more general version that fired all the delayed events rather than just the form submit.
A much simpler and effective way from my perspective should be :
function onPress_ENTER()
{
var keyPressed = event.keyCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
alert('enter pressed');
keyPressed=null;
}
else
{
return false;
}
}
A little simple
Don't send the form on keypress "Enter":
<form id="form_cdb" onsubmit="return false">
Execute the function on keypress "Enter":
<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">
Using TypeScript, and avoid multiples calls on the function
let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;
function SearchListEnter(event: KeyboardEvent) {
if (event.which !== 13) {
return;
}
// more stuff
}
<div class="nav-search" id="nav-search">
<form class="form-search">
<span class="input-icon">
<input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
<i class="ace-icon fa fa-search nav-search-icon"></i>
</span>
<input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
</form>
</div>
<script type="text/javascript">
$("#search_value").on('keydown', function(e) {
if (e.which == 13) {
$("#search").trigger('click');
return false;
}
});
$("#search").on('click',function(){
alert('You press enter');
});
</script>
native js (fetch api)
document.onload = (() => {
alert('ok');
let keyListener = document.querySelector('#searchUser');
//
keyListener.addEventListener('keypress', (e) => {
if(e.keyCode === 13){
let username = e.target.value;
console.log(`username = ${username}`);
fetch(`https://api.github.com/users/${username}`,{
data: {
client_id: 'xxx',
client_secret: 'xxx'
}
})
.then((user)=>{
console.log(`user = ${user}`);
});
fetch(`https://api.github.com/users/${username}/repos`,{
data: {
client_id: 'xxx',
client_secret: 'xxx'
}
})
.then((repos)=>{
console.log(`repos = ${repos}`);
for (let i = 0; i < repos.length; i++) {
console.log(`repos ${i} = ${repos[i]}`);
}
});
}else{
console.log(`e.keyCode = ${e.keyCode}`);
}
});
})();
<input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">
Add this Code In Your HTML Page...it will disable ...Enter Button..
Cross Browser Solution
Some older browsers implemented keydown events in a non-standard way.
KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.
which
and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.
The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
Minimal working example
JS
function isKeyPressed(event, expectedKey, expectedCode) {
const code = event.which || event.keyCode;
if (expectedKey === event.key || code === expectedCode) {
return true;
}
return false;
}
document.getElementById('myInput').addEventListener('keydown', function(event) {
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
});
HTML
<form>
<input id="myInput">
</form>
https://jsfiddle.net/tobiobeck/z13dh5r2/
Use event.preventDefault() inside user defined function
<form onsubmit="userFunction(event)"> ...
function userFunction(ev)
{
if(!event.target.send.checked)
{
console.log('form NOT submit on "Enter" key')
ev.preventDefault();
}
}
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
<input placeholder="type and press Enter" /><br>
<input type="checkbox" name="send" /> submit on enter
</form>
I used document on, which covers dynamically added html after page load:
$(document).on('keydown', '.selector', function (event) {
if (event.which == 13 || event.keyCode == 13) {
//do your thang
}
});
Added updates from #Bradley4

Submitting a form on 'Enter' with jQuery?

I have a bog-standard login form - an email text field, a password field and a submit button on an AIR project that's using HTML/jQuery. When I hit Enter on the form, the entire form's contents vanish, but the form isn't submitted. Does anyone know if this is a Webkit issue (Adobe AIR uses Webkit for HTML), or if I've bunged things up?
I tried:
$('.input').keypress(function (e) {
if (e.which == 13) {
$('form#login').submit();
}
});
But that neither stopped the clearing behavior, or submitted the form. There's no action associated with the form - could that be the issue? Can I put a javascript function in the action?
$('.input').keypress(function (e) {
if (e.which == 13) {
$('form#login').submit();
return false; //<---- Add this line
}
});
Check out this stackoverflow answer:
event.preventDefault() vs. return false
Essentially, "return false" is the same as calling e.preventDefault and e.stopPropagation().
In addition to return false as Jason Cohen mentioned. You may have to also preventDefault
e.preventDefault();
Don't know if it will help, but you can try simulating a submit button click, instead of directly submitting the form. I have the following code in production, and it works fine:
$('.input').keypress(function(e) {
if(e.which == 13) {
jQuery(this).blur();
jQuery('#submit').focus().click();
}
});
Note: jQuery('#submit').focus() makes the button animate when enter is pressed.
Return false to prevent the keystroke from continuing.
Is there any reason you have to hook and test for the enter key?
Couldn't you simply add a
<input type="submit" />
to your form and have it naturally be submitted when enter is pushed? You could even then hook the form's onsubmit action and call a validation function from there if you wanted...
You could even use the onsubmit as a test to see if your form is being submitted, but it won't work if you call form.submit().
Here's a way to do this as a JQuery plugin (in case you want to re-use the functionality):
$.fn.onEnterKey =
function( closure ) {
$(this).keypress(
function( event ) {
var code = event.keyCode ? event.keyCode : event.which;
if (code == 13) {
closure();
return false;
}
} );
}
Now if you want to decorate an <input> element with this type of functionality it's as simple as this:
$('#your-input-id').onEnterKey(
function() {
// Do stuff here
} );
You can also simply add onsubmit="return false" to the form code in the page to prevent the default behaviour.
Then hook (.bind or .live) the form's submit event to any function with jQuery in the javascript file.
Here's a sample code to help:
HTML
<form id="search_form" onsubmit="return false">
<input type="text" id="search_field"/>
<input type="button" id="search_btn" value="SEARCH"/>
</form>
Javascript + jQuery
$(document).ready(function() {
$('#search_form').live("submit", function() {
any_function()
});
});
This is working as of 2011-04-13, with Firefox 4.0 and jQuery 1.4.3
This is my code:
$("#txtMessage").on( "keypress", function(event) {
if (event.which == 13 && !event.shiftKey) {
event.preventDefault();
$("#frSendMessage").submit();
}
});
Also to maintain accessibility, you should use this to determine your keycode:
c = e.which ? e.which : e.keyCode;
if (c == 13) ...
Just adding for easy implementation. You can simply make a form and then make the submit button hidden:
For example:
<form action="submit.php" method="post">
Name : <input type="text" name="test">
<input type="submit" style="display: none;">
</form>
I use now
$("form").submit(function(event){
...
}
At first I added an eventhandler to the submit button which produced an error for me.
I found out today the keypress event is not fired when hitting the Enter key, so you might want to switch to keydown() or keyup() instead.
My test script:
$('.module input').keydown(function (e) {
var keyCode = e.which;
console.log("keydown ("+keyCode+")")
if (keyCode == 13) {
console.log("enter");
return false;
}
});
$('.module input').keyup(function (e) {
var keyCode = e.which;
console.log("keyup ("+keyCode+")")
if (keyCode == 13) {
console.log("enter");
return false;
}
});
$('.module input').keypress(function (e) {
var keyCode = e.which;
console.log("keypress ("+keyCode+")");
if (keyCode == 13) {
console.log("Enter");
return false;
}
});
The output in the console when typing "A Enter B" on the keyboard:
keydown (65)
keypress (97)
keyup (65)
keydown (13)
enter
keyup (13)
enter
keydown (66)
keypress (98)
keyup (66)
You see in the second sequence the 'keypress' is missing, but keydown and keyup register code '13' as being pressed/released.
As per jQuery documentation on the function keypress():
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
Tested on IE11 and FF61 on Server 2012 R2
As it may be late
but you can add below line in html:-
<input onkeyup="submitForm(event)" oninput="addTextName(this)" type="text" id="name-val">
and add this on js file
function submitForm(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 13){
toggleNextScreen();
}
}
keycode 13 means enter
In HTML codes:
<form action="POST" onsubmit="ajax_submit();return false;">
<b>First Name:</b> <input type="text" name="firstname" id="firstname">
<br>
<b>Last Name:</b> <input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="send" onclick="ajax_submit();">
</form>
In Js codes:
function ajax_submit()
{
$.ajax({
url: "submit.php",
type: "POST",
data: {
firstname: $("#firstname").val(),
lastname: $("#lastname").val()
},
dataType: "JSON",
success: function (jsonStr) {
// another codes when result is success
}
});
}
$('form#login').keypress(function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 13)
{
e.preventDefault();
$('form#login').submit();
return false;
}
});
Try this:
var form = document.formname;
if($(form).length > 0)
{
$(form).keypress(function (e){
code = e.keyCode ? e.keyCode : e.which;
if(code.toString() == 13)
{
formsubmit();
}
})
}

Categories

Resources