Unwanted form submit using jquery event [duplicate] - javascript

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?
I'm using HTML, PHP 5.2.9, and jQuery on the survey.

You can use a method such as
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:
function validationFunction() {
$('input').each(function() {
...
}
if(good) {
return true;
}
return false;
}
$(document).ready(function() {
$(window).keydown(function(event){
if( (event.keyCode == 13) && (validationFunction() == false) ) {
event.preventDefault();
return false;
}
});
});

Disallow enter key anywhere
If you don't have a <textarea> in your form, then just add the following to your <form>:
<form ... onkeydown="return event.key != 'Enter';">
Or with jQuery:
$(document).on("keydown", "form", function(event) {
return event.key != "Enter";
});
This will cause that every key press inside the form will be checked on the key. If it is not Enter, then it will return true and anything continue as usual. If it is Enter, then it will return false and anything will stop immediately, so the form won't be submitted.
The keydown event is preferred over keyup as the keyup is too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.key instead which returns the name of the key being pressed. When Enter is checked, then this would check 13 (normal enter) as well as 108 (numpad enter).
Note that $(window) as suggested in some other answers instead of $(document) doesn't work for keydown/keyup in IE<=8, so that's not a good choice if you're like to cover those poor users as well.
Allow enter key on textareas only
If you have a <textarea> in your form (which of course should accept the Enter key), then add the keydown handler to every individual input element which isn't a <textarea>.
<input ... onkeydown="return event.key != 'Enter';">
<select ... onkeydown="return event.key != 'Enter';">
...
To reduce boilerplate, this is better to be done with jQuery:
$(document).on("keydown", ":input:not(textarea)", function(event) {
return event.key != "Enter";
});
If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.
$(document).on("keydown", ":input:not(textarea)", function(event) {
if (event.key == "Enter") {
event.preventDefault();
}
});
Allow enter key on textareas and submit buttons only
If you'd like to allow enter key on submit buttons <input|button type="submit"> too, then you can always refine the selector as below.
$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
// ...
});
Note that input[type=text] as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.

Section 4.10.22.2 Implicit submission of the W3C HTML5 spec says:
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)
Therefore, a standards-compliant way to disable any implicit submission of the form is to place a disabled submit button as the first submit button in the form:
<form action="...">
<!-- Prevent implicit submission of the form -->
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<!-- ... -->
<button type="submit">Submit</button>
</form>
One nice feature of this approach is that it works without JavaScript; whether or not JavaScript is enabled, a standards-conforming web browser is required to prevent implicit form submission.

If you use a script to do the actual submit, then you can add "return false" line to the onsubmit handler like this:
<form onsubmit="return false;">
Calling submit() on the form from JavaScript will not trigger the event.

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:
var preventSubmit = function(event) {
if(event.keyCode == 13) {
console.log("caught ya!");
event.preventDefault();
//event.stopPropagation();
return false;
}
}
$("#search").keypress(preventSubmit);
$("#search").keydown(preventSubmit);
$("#search").keyup(preventSubmit);
You can combine all the above into a nice compact version:
$('#search').bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});

Use:
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.keyCode == 13) {
e.preventDefault();
return false;
}
});
This solution works on all forms on a website (also on forms inserted with Ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:
http://docs.jquery.com/Plugins/Validation
This will require more work than catching the Enter button, but surely it will provide a richer user experience.

I can't comment yet, so I'll post a new answer
Accepted answer is ok-ish, but it wasn't stopping submit on numpad enter. At least in current version of Chrome. I had to alter the keycode condition to this, then it works.
if(event.keyCode == 13 || event.keyCode == 169) {...}

A nice simple little jQuery solution:
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
return false;
}
});

A completely different approach:
The first <button type="submit"> in the form will be activated on pressing Enter.
This is true even if the button is hidden with style="display:none;
The script for that button can return false, which aborts the submission process.
You can still have another <button type=submit> to submit the form. Just return true to cascade the submission.
Pressing Enter while the real submit button is focussed will activate the real submit button.
Pressing Enter inside <textarea> or other form controls will behave as normal.
Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.
Thus:
<form action="...">
<!-- insert this next line immediately after the <form> opening tag -->
<button type=submit onclick="return false;" style="display:none;"></button>
<!-- everything else follows as normal -->
<!-- ... -->
<button type=submit>Submit</button>
</form>

It is my solution to reach the goal,
it is clean and effective.
$('form').submit(function () {
if ($(document.activeElement).attr('type') == 'submit')
return true;
else return false;
});

You can also use javascript:void(0) to prevent form submission.
<form action="javascript:void(0)" method="post">
<label for="">Search</label>
<input type="text">
<button type="sybmit">Submit</button>
</form>
<form action="javascript:void(0)" method="post">
<label for="">Search</label>
<input type="text">
<button type="sybmit">Submit</button>
</form>

Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.
Rather use this
<input type="button" onclick="event.preventDefault();this.closest('form').submit();">
than using this
<input type="submit">
Note: onclick is needed here to actually submit the form when clicked. By default, type="button" is not sufficient enough to submit.

Giving the form an action of 'javascript:void(0);' seems to do the trick
<form action="javascript:void(0);">
<input type="text" />
</form>
<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
alert('Hello');
}
});
});
</script>

Do not use type="submit" for inputs or buttons.
Use type="button" and use js [Jquery/angular/etc] to submit form to server.

This is the perfect way, You will not be redirected from your page
$('form input').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});

I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.
<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />
And this jQuery code:
$('.idNoEnter').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
Alternatively, if keydown is insufficient:
$('.idNoEnter').on('keypress keydown keyup', function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
Some notes:
Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.
I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

You could make a JavaScript method to check to see if the Enter key was hit, and if it is, to stop the submit.
<script type="text/javascript">
function noenter() {
return !(window.event && window.event.keyCode == 13); }
</script>
Just call that on the submit method.

There are many good answers here already, I just want to contribute something from a UX perspective. Keyboard controls in forms are very important.
The question is how to disable from submission on keypress Enter. Not how to ignore Enter in an entire application. So consider attaching the handler to a form element, not the window.
Disabling Enter for form submission should still allow the following:
Form submission via Enter when submit button is focused.
Form submission when all fields are populated.
Interaction with non-submit buttons via Enter.
This is just boilerplate but it follows all three conditions.
$('form').on('keypress', function(e) {
// Register keypress on buttons.
$attr = $(e.target).attr('type');
$node = e.target.nodeName.toLowerCase();
if ($attr === 'button' || $attr === 'submit' || $node === 'textarea') {
return true;
}
// Ignore keypress if all fields are not populated.
if (e.which === 13 && !fieldsArePopulated(this)) {
return false;
}
});

ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:
window.addEventListener('keydown', function(event) {
//set default value for variable that will hold the status of keypress
pressedEnter = false;
//if user pressed enter, set the variable to true
if (event.keyCode == 13)
pressedEnter = true;
//we want forms to disable submit for a tenth of a second only
setTimeout(function() {
pressedEnter = false;
}, 100)
})
//find all forms
var forms = document.getElementsByTagName('form')
//loop through forms
for (i = 0; i < forms.length; i++) {
//listen to submit event
forms[i].addEventListener('submit', function(e) {
//if user just pressed enter, stop the submit event
if (pressedEnter == true) {
updateLog('Form prevented from submit.')
e.preventDefault();
return false;
}
updateLog('Form submitted.')
})
}
var log = document.getElementById('log')
updateLog = function(msg) {
log.innerText = msg
}
input,
textarea {
display: inline-block;
margin-bottom: 1em;
border: 1px solid #6f6f6f;
padding: 5px;
border-radius: 2px;
width: 90%;
font-size: 14px;
}
input[type=submit] {
background: lightblue;
color: #fff;
}
<form>
<p>Sample textarea (try enter key):</p>
<textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>
<p>Sample textfield (try enter key):</p>
<input type="text" placeholder="" />
<br/>
<input type="submit" value="Save" />
<h3 id="log"></h3>
</form>

If you're using Alpine, you can use the following to prevent form submission by pressing Enter:
<div x-data>
<form x-on:keydown.prevent.enter="">...</form>
</div>
Alternatively you can use the .window modifier to register the event listener on the root window object on the page instead of the element.
<form>
<div x-data>
<input x-on:keydown.window.prevent.enter="" type="text">
</div>
</form>

I have use this Code to disable 'ENTER' key press on both input type [text] and input type [password], you can add other too like input type [email] or also can apply on your desired Input type.
$(document).on('keyup keypress', 'form input[type="text"] , input[type="password"]', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});

$(document).on("keydown","form", function(event)
{
node = event.target.nodeName.toLowerCase();
type = $(event.target).prop('type').toLowerCase();
if(node!='textarea' && type!='submit' && (event.keyCode == 13 || event.keyCode == 169))
{
event.preventDefault();
return false;
}
});
It works perfectly!

If using Vue, use the following code to prevent users from submitting the form by hitting Enter:
<form #submit.prevent>...</form>

I had a similiar problem, where I had a grid with "ajax textfields" (Yii CGridView) and just one submit button. Everytime I did a search on a textfield and hit enter the form submitted. I had to do something with the button because it was the only common button between the views (MVC pattern). All I had to do was remove type="submit" and put onclick="document.forms[0].submit()

I think it's well covered with all the answers, but if you are using a button with some JavaScript validation code you could just set the form's onkeypress for Enter to call your submit as expected:
<form method="POST" action="..." onkeypress="if(event.keyCode == 13) mySubmitFunction(this); return false;">
The onkeypress JS could be whatever you need to do. There's no need for a larger, global change. This is especially true if you're not the one coding the app from scratch, and you've been brought into fix someone else's web site without tearing it apart and re-testing it.

Something I have not seen answered here: when you tab through the elements on the page, pressing Enter when you get to the submit button will trigger the onsubmit handler on the form, but it will record the event as a MouseEvent. Here is my short solution to cover most bases:
This is not a jQuery-related answer
HTML
<form onsubmit="return false;" method=post>
<input type="text" /><br />
<input type="button" onclick="this.form.submit()" value="submit via mouse or keyboard" />
<input type="button" onclick="submitMouseOnly(event)" value="submit via mouse only" />
</form>
JavaScript
window.submitMouseOnly=function(evt){
let allow=(evt instanceof MouseEvent) && evt.x>0 && evt.y>0 && evt.screenX > 0 && evt.screenY > 0;
if(allow)(evt.tagName=='FORM'?evt.target:evt.target.form).submit();
}
To find a working example: https://jsfiddle.net/nemesarial/6rhogva2/

Using Javascript (without checking any input field):
<script>
window.addEventListener('keydown', function(e) {
if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
e.preventDefault();
return false;
}
}, true);
</script>
If someone wants to apply this on specific fields, for example input type text:
<script>
window.addEventListener('keydown', function(e) {
if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
e.preventDefault();
return false;
}
}
}, true);
</script>
This works well in my case.

Go into your css and add that to it then will automatically block the submission of your formular as long as you have submit input if you no longer want it you can delete it or type activate and deactivate instead
input:disabled {
background: gainsboro;
}
input[value]:disabled {
color: whitesmoke;
}

This disables enter key for all the forms on the page and does not prevent enter in textarea.
// disable form submit with enter
$('form input:not([type="submit"])').keydown((e) => {
if (e.keyCode === 13) {
e.preventDefault();
return false;
}
return true;
});

Related

On ENTER keyup - Execute Function inside form and not submit the form

I have a table with filterable data using the jQuery DataTables library.
This table is inside a form that, when rows are CHECKED (in one column there is a checkbox), the SUBMIT button will add them to a collection.
Attached to the table is a custom search filter that functions like the built-in search filter that comes with DataTables, but instead of a "filter as you type" functionality, I have a submit button attached so that it will not filter the table results until you click the button. There is some functionality added to that search filter that actually runs an ajax call to a database, and to reduce the amount of calls to the database, I put the button on the search filter and disabled the "filter as you type" functionality.
I STILL want to be able to click the ENTER key on my keyboard when I have finished typing in my search filter to execute this custom search, but I am unable to stop the form from submitting. I have the custom search filter in a function called "tableFilter()". The ID of the form is "#addtitle"
$("#addTitle").on('keyup', function(e){
var keyCode = e.keyCode || e.which;
console.log('keyup');
if (keyCode == 13){
console.log('ENTER PRESSED');
if ($("#dataTables_filter_input").is(":focus")){
console.log('FILTER FOCUS');
tableFilter();
e.preventDefault();
return false;
}
}
});
I figured that if the input field of the search was still in focus, that would be enough of a difference for the code to know that when I click ENTER, it would execute the search filter and not submit the form - yet the form still submits.
Do I have things out of order? Am I not calling the right functions?
we must know the mechanical first.
<form>
<input type="text">
<input type="submit">
</form>
if you pressed ENTER in input text. it will trigger:
button submit clicked
form submitted
input text keyup [ENTER]
if you want prevent default behaviour. You must use preventDefault() on $('form').submit [only], in other word you dont need type preventDefault() in $('input[type="submit"]').click or $('input[type="text"]').keyup
so, your jquery will like this
$('form').submit(function(e){
e.preventDefault();
})
$('input[type="text"]').keyup(function(e){
var keyCode = e.keyCode || e.which;
if (keyCode == 13){
//do something
}
})
but you will never can use submit button to trigger form input. To do form submit you must use type="button" to trigger form submit.
Demo: http://jsbin.com/pirepahuhu/edit?html,output
===============
this what i think to force solved this problem
demo: http://jsbin.com/hiqatetoti/2/edit?html,output
<form>
another text input<input type="text"><br>
add title<input type="text" id="addTitle"><br>
another text input<input type="text"><br>
<input type="button" value="button"><br>
<input type="submit" value="submit"><br>
</form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<Script>
$(function(){
$("#addTitle").on('keyup', function(e){
var keyCode = e.keyCode || e.which;
if (keyCode == 13){
console.log("ENTER PRESSED on input text");
}
});
$('form').submit(function(e){
e.preventDefault();
if($(this).find('#addTitle').is(':focus') === false){
doAjaxForm();
}
});
function doAjaxForm(){
console.log('do ajax form');
}
})
</script>
if form submitted but #addTitle has focused = do nothing, then addTtitle keyup will do your job
if form submitted but #addTitle not focussed = do ajax form
if you press enter on another text input (except #addTitle) , this will trigger form submit = do ajax form
if submit button clicked = do ajax form
i hope this will work for you, since you dont give us your datatables script.
let cancelEvent = function (e) {
e.preventDefault();
return false;
};
let filter = document.getElementById('dataTables_filter_input');
let addTitle = document.getElementById('addTitle');
let form = document.querySelector('form');
form.addEventListener('submit', cancelEvent);
addTitle.addEventListener('keyup', function(e) {
let keyCode = e.keyCode || e.which;
console.log('KEYUP');
if (keyCode !== 13 || !filter.is(':focus')) {
console.log('NOT ENTER PRESSED OR FILTER NOT FOCUS');
return true;
}
tableFilter();
e.preventDefault();
return false;
});

javascript keypress multiple records problems

I would like to ask why it will have multiple response? How can i enter the input field with just one response?
Expectation : Input the data in input field and press the enter , it will execute the actions.
$("#textInput").keypress(function (e) {
console.log("123");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type='text' id='textInput'/>
You have syntax error in you code. closing should be }); instead of )};
$("#textInput").keypress(function (e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textInput">
Expectation : Input the data in input field and press the enter , it will execute the actions.
In order to submit the corresponding form as soon as the user enters a text string and a final enter key you can:
test if current char is the enter key (e.which == 13)
get the closest form
submit the form
$("#textInput").on('keypress', function (e) {
if (e.which == 13) {
$(this).closest('form').submit();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/action_page.php">
Enter text and type enter to submit:<br>
<input type="text" name="textInput" value="">
</form>
I think, you should have choose other event,like onblur to fix your problem
$("#textInput").on('blur',function (e) {
console.log("123");
)};
In your code ,keypress events gives you output,in every keypress action,So this is the reason you got multiple responses
And next,if you think,if you want to press Enter button then need response,In this case little changes will helps you
$("#textInput").keypress(function (e) {
if(e.which == 13) {
console.log("123");
}
});
The keypress event is sent to an element when the browser registers keyboard input.
— jQuery Documentation link
What you really want is .submit() as they are the one that will only be triggered when the user submits info.
$("#textInput").submit(function (e) {
console.log("123");
)};
Or if you only want to detect enter keypress but not submit, use this:
How to detect pressing Enter on keyboard using jQuery?

How do I use JavaScript or jQuery to submit a form by using the Enter key, when not the default form action

I have a page that has three "forms" that are apparent to the user. Under the hood, the page has only ONE form, using html:form as the JSP object controlling the entire page. When a user clicks on the image that is used for the individual submit buttons, it triggers an onClick() function, which bypasses the form's action and executes another action instead.
<html:form action="foo.do">
<html:text property="name" styleClass="input" />
<img src="bar.jpg" onClick="myFunction();" />
</html:form>
<script>
function myFunction(){
document.forms[0].action = "realPage.do";
document.forms[0].submit();
}
</script>
This script works, sending the user not to the default "foo.do" but rather to the destination of the function (realPage.do)
However, the problem is my users want to be able to submit the form just by hitting 'Enter' on their keyboard when in any one of the fields, of the particular "form" they want to submit. How can I use JavaScript or jQuery to recognize which "form" and, hence, which input field the user is in, detect the press of the 'Enter' key and submit using the same function as the button?
This should solve your problem
$(document).ready(function(){
$("input").keyup(function (e) {
if (e.keyCode == 13) {
// Submit your form here
}
});
});
I would probably arrest the form submit and detect which element has focus. Something like this, where each pseudo-form has an identified wrapper element:
$(function() { // document.ready
$('#myform').submit(function(event) {
event.preventDefault();
if ( $('#pseudoForm1 input').is(':focus') ) { ... }
else if ( $('#pseudoForm2 input').is(':focus') ) { ... }
else if ( $('#pseudoForm3 input').is(':focus') ) { ... }
});
});
You could start with this -
$('input').keypress(function(e) {
if(13 == e.keyCode) {
var closestForm = $(this).closest('form');
$(closestForm).submit();
}
});

Stop Enter/Return key submitting a form [duplicate]

This question already has answers here:
Prevent users from submitting a form by hitting Enter
(36 answers)
Closed 6 years ago.
I have a table within a form. The table contains some form fields, but there are form fields outside of the table (but still within the form) too.
I know that Enter and Return are traditionally used to submit a form via the keyboard, but I want to stop this behaviour for fields within the table. For example, if I focus a field within the table and hit Enter/Return, nothing happens. If I focus a field outside of the table (but still within the form) then for it to submit as normal.
I have a jQuery plugin that targets this table. Simplified, this is what I've tried this far:
base.on('keydown', function(e) {
if (e.keyCode == 13) {
e.stopPropagation();
return false;
}
});
Where base is the table jQuery object. This is within my plugin's init method. However, hitting Enter still submits the form.
Where am I going wrong?
EDIT: Some simplified HTML:
<form method="" action="">
<input type="text" /><!--this should still submit on Enter-->
<table>
<tbody>
<tr>
<td>
<input type="text" /><!--this should NOT submit on Enter-->
</td>
</tr>
</tbody>
</table>
</form>
base.keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13)
return false;
});
or for only inputs:
$(':input', base).keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13)
return false;
});
I'm going to guess that a form element will fire the submit event, it doesn't bubble up through the table and on to the form, try this instread:
$('input, select, textarea', base).on('keydown', function(e) {
if (e.keyCode == 13) {
return false;
}
});
Note we're also providing context to the selector, so this keyDown will only occur on elements (modify as required) within your table.
As gordan said in another comment, return false does both .preventDefault() and .stopPropagation()
e.preventDefault() rather than e.stopPropagation(). stopPropagation only stops it bubbling up to higher DOM nodes, it doesn't prevent the default action.
I found this Q/A trying to sort out a similar situation where I have multiple forms and enter would not do what I wanted. In my specific case, I would dynamically add a new <div id="D1"> D1, D2, D3, etc, and each new div has a form that would reload that div from the same php code that created it, only also with a POST.
Unrelated first problem was I couldn't dynamically create a new function with each div, so I passed the D1, etc, descriptor as an argument to the Javascript function:
<script type="text/javascript">
function formSubmit ( divid ) {
// post data
event.preventDefault();
$.post( "make-my-form-div.php",
$("#form"+divid).serialize(),
function(data){
$("#"+divid).html(data);
});
return false;
}
</script>
You will see the requisite event.preventDefault(); and return false; that works for the answers in this thread. It didn't work for me. If I click the Submit in any one form, that one div would reload with the correct data. Hitting enter would cause default action and reload the entire page, leaving me with only 1 div.
This Answer worked: I needed a unique ID and NAME for the different forms. Initially, they were <INPUT TYPE="button" VALUE="Submit" onClick="formSubmit('<?php echo $divid ?>');"> but once I added unique ID and NAMES, such as "formD1", etc, it all started working correctly.
This works for me.
$("input[type='text']").on('keypress', function(e) { return e.keyCode != 13; });
Just put below code in your template file or in header of page.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>

Preventing form submission when Enter is pressed [duplicate]

This question already has answers here:
How to prevent ENTER keypress to submit a web form?
(29 answers)
Closed 6 years ago.
I have a form with a disabled submit button. Even though the user can't press this button, he can still hit Enter to submit the form. How do I prevent that?
If you want to completely disable the form submit (However I am wondering why the whole <form> element is then there in first place), then you need to let its submit event handler return false.
So, basically:
<form onsubmit="return false;">
You can add it using Javascript/DOM manipulation during onload as previous answerers pointed out.
If you only want to disable the Enter key to submit the form, then you need to let its keydown event handler return false when the key of the event matches Enter (this one is crossbrowser compatible and covers both the default Enter as well as the numpad Enter!).
<form onkeypress="return event.key != 'Enter';">
This however also disables the Enter key in any <textarea> elements in the form. If you have any of them and you would like to keep them functioning, then you'll need to remove the onkeydown from the <form> and copy it over all <input> and <select> elements. jQuery can be helpful in this:
$('input, select').keydown(event => event.key != 'Enter');
See also:
Prevent users from submitting a form by hitting Enter
Assuming HTML:
<form id="myForm"> ...
You can do this with JavaScript:
document.getElementById("myForm").onsubmit = function () {
return false;
};
Instead of implementing two methods of disabling form submitting, add an event handler to form's onsubmit which will check the disabled property of the button:
myForm.onsubmit = function () {
if (myForm.mySubmit.disabled)
return false;
}
Say you had a form with an id of "myForm":
<form id="myForm" action="some_file" method="post">
...
</form>
<script type="text/javascript">
document.getElementById( "myForm").onsubmit = function() {
return false;
};
//or with jQuery: $( '#myForm' ).submit( function() { return false; } );
</script>
If you don't want to edit the onsubmit event of the form, you can do it like this.
Add this to the text input:
onKeyPress="return noEnter(event)"
And this to the header:
function noEnter(e)
{
var key;
// firefox vs. ie
(window.event) ? key = window.event.keyCode : key = e.which;
(key == 13) ? return false : return true;
}
easier to pull of with jquery.
jQuery Solution:
$(document).ready(function(){
$('form[name="form"]').keypress( function(evt){
return !(evt.which==13 && evt.target.type!='textarea');
});
$('form[name="form"] input[type="submit"]').attr('tabIndex',-1); // this prevents submit also by spacebar (keyCode==32)
//$('form[name="form"]').submit(function(){ alert('test'); return false; }); // test
});
document.getElementById("myForm").onsubmit = function () {
return false;
};
These codes doesn't work on Chrome and Safari. It submits form to action url.
But <form onsubmit="return false;"> is useful.

Categories

Resources