HTML capture enter key and tab key - javascript

I want to prevent the enter key from submitting the form, I want it to act as a TAB key to just jump to the next field in the form or the next element.
Is this possible in HTML/JS?
if not possible to make the enter button act as a tab, is there a way to prevent the submission of the form and make only the form be submitted using the buttons on the HTML??
EDIT:
I have received a solution to this problem when I was asking for another problem!
here you can find the solution.

For accessibility/usability reasons, you really shouldn't prevent the Enter key from submitting the form (assuming the browser was going to do that anyway; IIRC, some older browsers didn't).
Assuming that you want to do this because the submit button has a click handler you'd like to happen for every form submission, you should instead move that code into a separate function and invoke it from a the form's submit event.
In jQuery, it would look something like:
$('#myForm').submit(function(e) {
if (!isValid()) {
e.preventDefault(); // Could also be `return false;` but I prefer preventDefault.
}
});
See the docs.
FYI, if you're trying to do some validation, you should check out the validation plugin.

<html>
<body>
<script>
function tmpFn(val){
if(event.keyCode=='13'){
if (val<4)
document.forms["yourform"].elements["box" + (val+1)].focus();
else
document.yourform.submit();
return false;
}
return true;
}
</script>
<body>
<form name="yourform" action="#">
<input type="text" name="box1" onkeypress="return tmpFn(1)"><br>
<input type="text" name="box2" onkeypress="return tmpFn(2)"><br>
<input type="text" name="box3" onkeypress="return tmpFn(3)"><br>
<input type="text" name="box4" onkeypress="return tmpFn(4)"><br>
<input type="submit" name="done" value="Submit">
</form>
</body>
</html>
EDIT: Refrain from using 'eval'.. Thanks Tim and Andy!

It might be possible to solve this using some jQuery - although I don't know how to imitate a keypress.
$(document).keyup(function(e) {
if(e.keyCode == 13)
{
//Code to imitate keypress of Tab key
}
});
Edit: Made a quick jsFiddle to "imitate" tab presses, which would go to the next field like you mentioned. (This one works based on the Enter key being pressed in a field)
jsFiddle

Off the top of my head, to prevent the enter button from submitting the form, don't use a submit button, rather use a <input type="button" ... onclick="submitForm();"> to call javascript to submit the form. I could be wrong, but I believe this should prevent pressing enter on any other element submitting the form.

Related

Can't Get Form to Submit Properly [duplicate]

The title speaks for itself... I have a couple of forms, one of them is just a single text input form and the other one is composed by two text inputs. I do not want any submit button in any of them, I want each form to submit whenever the user presses the ENTER button at any text input:
The form composed by just one input submits everytime the user presses the ENTER button - Perfect!
The second form composed by two text inputs does not behave this way, it does not submit when the user presses the ENTER button at any of both inputs.
Is there a way to make a form with more than one text input behave this way and avoid having a submit button in it?
Try adding this between the <form></form> tags
<input type="submit" style="display: none" />
Tested it and it works on Firefox and Chrome. If you have a submit input type in the form, enter should automatically submit it, regardless of whether it's visible or not.
I am actually using this myself in a login form, though in the username field, it makes more sense to move to the next field than to submit. Just in case you have a similar use case, here's the code I used (requires jQuery)
$('#username').keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
$('#password').focus();
event.preventDefault();
}
});
Note that there is a slight bug though -- if the user selects a browser autocomplete username and presses enter, it still moves to the next field instead of selecting it. Didn't have time to debug this, but if someone can figure out how to fix it, that would be cool.
I was looking for a solution to this problem and want to share my solution, based on many posts over here. (Tested on modern Chrome/Firefox/IE)
So, using only Javascript the follow code submits the form if ENTER key is pressed on any field or if the button Submit is pressed. After that it clear/reset the form, which is a nice thing to do.
Hope it helps.
<!DOCTYPE html>
<html>
<body>
<p>Based on http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit</p>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<div onKeyPress="return myFunction(event)">
<form id="form01" action="demo_form.asp" onsubmit="return false;" >
Enter name: <input type="text" name="fname">
<input type="button" value="Submit" onclick="myFunction(0)">
</form>
</div>
<script>
function myFunction(e) {
if((e && e.keyCode == 13) || e == 0) {
alert("The form was submitted");
document.forms.form01.submit();
document.forms.form01.fname.value = ""; // could be form01.reset as well
}
}
</script>
</body>
</html>
Be sure that your inputs are inside "form" element and give the "form" element an "action" attribute.
You will have to look for the Enter key press. This post here shows how to do that.
Enter key press event in JavaScript
You can use the code below to submit a form after pressing Enter.
<input id="videoid" placeholder="Enter the video ID">
<button id="mybutton" type="button" onclick="myFunction()">Submit</button>
<script>
var input = document.getElementById("videoid");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("mybutton").click();
}
});
</script>

how do i trigger a button with the enter key in java script?/ how to give text box and search button an ID?

Sorry i know this question has been asked and answered before but i can't seem to implement it into my code. very new to programming and struggling quite a bit.
Pretty simple stuff here i have a search bar and a search button. What i am trying to do is instead of having to physically click the search button to search for what i want, i would like to have the ability to be able to click the enter key which could search as well. Here is the code for the search bar and button.
Easy stuff.
<div class="ui-widget"> <!-- only for css purposes-->
<input id="search"> <!-- for the search box-->
<button type="button" onclick="searchresult()">Search</button> <!-- search button-->
</div>
So at the moment when you click the search button it will activate the javascript function i have which is:
function searchresult() {
//find the result
}
which in turn will find the result you want. deadly stuff.
I haven't included the code which is inside the javascript function as we don't need it for this question and its quite lengthy.
so basically i want the enter key to be able to activate the searchresult javascript function the same way the search button does.
I am aware that you can use jQuery keypress() Method to do this. and here is the code which can be used to do what i am wondering but i just don't know how to implement it into what i have:
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});
I am aware of the id attribute which is used in HTML coding as well but i don't know how i would go about correctly assigning the search button and text box an id each which then i could use in the code i have just above which then in turn would allow me to use the enter key as search as well.
So if anyone could just show me how i could use the jQuery code i found to solve my question that would be brilliant. Completely open to any other suggestions about how i would go about it either.
Thank you everyone for your time and attention!
Use the following code (explanation below):
function searchresult() {
console.log('searching');
//find the result
}
$("#search").keyup(function(event) {
if (event.keyCode == 13) {
$("#searchButton").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui-widget">
<input id="search">
<button type="button" id="searchButton" onclick="searchresult()">Search</button>
</div>
What this does is it will hook up an event to the input box with the id search and whenver it receives a keyup (key release) event, it will check if it is the Enter key and, if so, fire the click event of the button with id searchButton (I added that id as an example). Your search button's click event is hooked up to the searchResult() function, which is in turn called from that.
If you need more information on how event handling works in jQuery, check out jQuery's Handling Events page.
You really should consider using a form.
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
$(function(){
$("#search").on("submit", function(e){
search_function($("#search_terms").val());
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
Or here is an example in pure JS
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("search")
.addEventListener("submit", function(e){
search_function(document.getElementById("search_terms").value);
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
}, false);
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
You can assign the id to your search button :
<button type="button" onclick="searchresult()" id="search_key">Search</button>
Then you can trigger the click action on button using jQuery#trigger
JS :
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode == 13) {
$("#search_key").trigger('click');
}
})
$('#search").change(function() {
searchResult();
});
Don't even bother with looking for the "enter" key; just watch for the input value to change (which would happen upon pressing enter, or blurring the field).
You can use a form and it's onsubmit event since you want enter key and submit click to do the same thing.
<form action="" method="" onsubmit="searchresult(this);">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
But don't forget to use event.preventDefault() or return false.

keyup 13 event repeats implied submission - submit form on enter issue

UPDATE 10/9/15
My original question is below and is unclear and does not fully describe my problem because it focuses on the keyup event listener when its actually the double submission of the form (once from the change event and once from the implicit submission both triggered by keypress of the enter key) as the root problem... I have reviewed the code some more and here is an example demonstrating my true problem:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<form method="GET" action="#">
<input type="text" />
<input type="submit" />
</form>
<script>
$('form>input[type="text"]')
// Change event triggered by both enter key and tab key
.on('change', function (e) {
e.preventDefault();
console.log('change event');
$('form').submit(); //This emulates a more complex ajax request
});
$('form').submit(function (e) {
// You will notice the console logs this twice if you hit enter instead of tab.
console.log("form submitted");
});
</script>
</body>
</html>
If you enter something into the input box and hit the enter key then you will see in the console that the form submits twice, once from the change event and once from the implicit submission of the browser.
I want to stop the form submitting twice (you will notice I have already tried preventDefault in my code above). The answer appears to be to preventDefault specifically on the keypress (not keyup) of the enter key (many thanks to #JotaBe)
ORIGINAL QUESTION
So I have an event listener for the enter key on an input something like so
$(element)
.on('keyup', function (e) {
if (e.which === 13) {
event.trigger();
}
}); `
Specifically the code is from this plugin
This is interfering with the implied submission which is standard on most browsers, as per the W3 standard, and causing the form to submit twice.
What I would like to know, does the implicit submission happen before or after the explicit submission of my form with the event listener?
And for bonus points which version (or where can I find out which version) did 'implicit submission' get added to various browsers? (so I know how far back my code will be compatible)
Second question first
The implicit submission, although not with that name, exists at least from something as old as HTML 2 specs of novemeber 1995. Last lines of section 8.2:
When there is only one single-line text input field in a form, the user
agent should accept Enter in that field as a request to submit the form.
So, as we say in Spain, is as old as coughing.
And then, the main stuff
When you handle an event, unless you cancel the default action, when the code in your handler finishes running, the default action is executed.
Your code is triggering the event, and not cancelling the defautl action. That's why the submission happens twice, once for the handled event, and once for the additional triggered event.
In the case of jquery you've got to call event.preventDefault() to avoid the default action to execute.
Please look at this fiddle to check 2 things:
1) By default, when you press enter on a form, the form is submitted To be more precise, it must simulate a click on the first submit button of the form. Thus, if this button is disabled, or doesn't exist, nothing happens.
2) If you want to prevent the default behavior, you must handle the keypress (not keydown or keyup) event on the textbox, and invoke the event's preventDefault method.
3) According to the specs, this should only happen when there is a single textbox (of type text, number, date, url,email, etc.). But it doesn't work like this in most browsers, for example in desktop versions of Chrome 45, IE 10 and FF27 & FF33. I didn't test other versions.
Fiddle code:
// This suppres the default behavior of submitting the
// form when the enter key is pressed in the textbox
$('#form2').on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
console.log('key press 13');
}
});
// This event is triggered when any form is submitted
// (in fact, the submission is prevented).
$('form').on('submit', function(e) {
console.log('Sending form', e.target.name);
e.preventDefault();
});
with this HTML:
<div>
<p>Form 1, default enter behavior, when there is only a textbox, and there is a submit button</p>
<p>If you press enter, it's submitted</p>
<form method="GET" id="form1">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 2: prevents default behavior on textbox</p>
<p>If you press enter the form is not submitted</p>
<form method="GET" id="form2">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 3: submit shuld only happen if there is only one textbox, but it depends on the browser</p>
<p>If you press enter the form should not be submitted, because there are several textboxes, but I bet it will be submitted</p>
<form method="GET" id="form3">
<input type="text" />
<input type="text" />
<input type="submit" />
</form>
</div>
add global variable like
var submited = true;
validate like
$(element)
.on('keyup', function (e) {
if (submited) {
submited = false ;
event.trigger();
}
});

Accidental JavaScript redirct?

I have a form that adds an item to a list when I press enter or hit a submit button. I'm not sure what I've changed, but suddenly pressing enter seems to redirect the URL, while clicking the button acts normally.
The HTML portion looks like this:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
</form>
The jQuery is:
$('#check').click(function () {
addIngredient('new-ingredient');
});
$('.new-ingredient').keypress(function (e) {
if (e.keyCode == 13) {
addIngredient('new-ingredient');
}
});
So it's running the same function either way. In both cases, it successfully adds the ingredient to the list, but in the 2nd case, the page is redirected from "recipe.html" to "recipe.html?new-ingredient=".
And here's the part that really confuses me: when I add an extra input to the form, this problem doesn't occur when I press enter in either box:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<input type="text"></input>
</form>
Also, if I add in an actual button (not my clickable image), it redirects like pressing enter, even though I have no code to do anything if the button is pressed. In this case, the extra input field has no effect.
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<button id="button">Add Ingredient</button>
</form>
I have absolutely no idea why this is happening. Even if I get rid of the jQuery to perform an action when I hit enter, this still happens. I'm new to JavaScript, so sorry if this is something obvious, but I'd really appreciate some help.
I can also provide more of my code if it's relevant, but I didn't want to clog things up with a ton of code.
Hitting enter (or clicking the button if its there) is submitting the form (this makes it appear to "redirect the URL"). You need to prevent that from happening with e.preventDefault(). So in the click listener:
$('#button').click(function(e){
e.preventDefault();
addIngredient('new-ingredient');
});
Put that in each of the listeners, or get rid of your form tags so there isn't anything to submit (as was mentioned in the comments).
I don't entirely blame you for being confused. The browser default behavior is to perform the "submit" action, whatever it is, when someone presses enter while a field in the form is highlighted. As elclanrs said, you can override the submit action; in fact, I'm pretty sure in JQuery it's just this:
$('#add-ingr').submit(function(e) {
if ('event is not coming from button')...{
e.preventDefault();
}
});
I'm afraid I couldn't explain why adding a blank input changed the effect, though. Through my laziness, I have also left you the work of determining the best way of allowing actual submissions, though (if the form gets submitted to the server, you won't want to block submit every time)

BlackBerry 10 browser submits form using browser submit button when using preventDefault

As I'm working on a mobile version of our company website I ran into, what I believe is, an issue with the BlackBerry 10 browser. (I'm using the Q10, version 10.1.0.4181)
I'm using jQuery to bind to the submit event on a form to do an AJAX call, so I have a preventDefault, but it seems that BB10 seems to ignore this when using the SUBMIT button the browser provides.
It works fine when pressing the enter key or pressing the submit button of the form, but when I press the Submit button which is at the bottom of my browser (alongside with the previous/next buttons) it ignores the preventDefault (and return false) and still continues on submitting the form.
I've set up a jsfiddle which demonstrates this:
http://jsfiddle.net/e4AHZ/4/
The code I'm using to bind is:
$(function () {
$(document).on('submit', 'form', function (e) {
e.preventDefault();
alert('done!');
return false; // as final resort, no luck =(
});
});
Anyone else who had this issue? Is there a possible fix/workaround?
Thanks!
I have worked around this by adding action="javascript:void(0);" to you form (see updated fiddle http://jsfiddle.net/e4AHZ/11/).
I do not know if this is good enough but action="javascript:void(0);" is in fact part of a solution given to a similar question.
<form method="post" action="javascript:void(0);">
<input type="text" name="field1" value="some msg" />
<input type="text" name="field2" value="some msg" />
<input type="submit" />
</form>
You can also set the action to "javascript:ajaxfunction();" where "ajaxfunction()" is the function you want to call to submit the form:
$('form').attr("action","javascript:ajaxfunction();");
This should allow you to take advantage of that submit button.

Categories