I'm having an issue with my chat bot app where a line break is being inserted into the form after the user is pressing the submit button. To clarify, the message is being sent, but then creating a line break so the user has to backspace for the form to be completely empty.
var enableEnterKey = function() {
$(document).keypress(function(e) {
if($('#maxx-message-box').is(':focus') && e.keyCode === 13) {
var message = $('#maxx-message-box').val();
sendMessage(message);
}
});
This is our function. Please help.
You probably need something like:
$("#maxx-message-box").keypress(function (e) {
if (e.keyCode != 13) return;
var message = $("#maxx-message-box").val().replace(/\n/g, "");
if (!!message)
{
sendMessage(message);
$("#maxx-message-box").val("");
}
return false;
});
how to disable the "enter" key who give us the possibility to valid and send the form if the field is not valid ?
I only did the first part, which indicates that the field is not valid, but the "enter" key is always active . So my question is simple, how to disable the "enter" key button from the moment we see the "error-message" under the field
here is my test page ->
http://500milligrammes.com/facticemagazine/final/unsubscribe/
I've checked your website, to achieve what you asked for:
$("#name").on("keydown", function(e) {
if(e.which === 13 && $("#name").next(".error-message").is(":visible")) {
e.preventDefault();
return false;
}
});
The submit is always send on keydown, so we need to add a keydown event handler.
Next is to check if the key was the enter key e.which === 13 and after that we just need to check if the error message is shown or not $("#name").next(".error-message").is(":visible").
If both conditions are true then just prevent the default action (submit) by calling e.preventDefault();
You can further improve this by also checking if the input is empty or not before accepting the enter key. The first keydown might be the enter key.
$("#name").on("keydown", function(e) {
if(e.which === 13) {
if($("#name").next(".error-message").is(":visible") || !$("#name").val()) {
e.preventDefault();
return false;
}
}
});
You can check it using the keycode value (13) of enter key.
Something like the following should do:
$('form').on('keyup keypress', function(e) {
if (e.which == 13) {
if (!isValid()) { // your validation function
e.preventDefault();
return false;
} else {
$(this).submit();
}
}
});
Try adding this when you show the error:
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.which == 13) {
e.preventDefault();
return false;`enter code here`
}
});
I have an HTML form with several text fields. So, I want to move cursor from a text field to next text field when I press the enter key, but the form should not be submitted. How can I do this? If there is a code example it may more helpful to me.
press the tab key on your keyboard instead of enter.
I'm using this function to do what you ask for:
$(document).on("keypress", ".TabOnEnter" , function(e)
{
if( e.keyCode == 13 )
{
var nextElement = $('[tabindex="' + (this.tabIndex+1) + '"]');
console.log( this , nextElement );
if(nextElement.length )
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
Use the 'TabOnEnte' class on the fields you want this class to apply on.
Also to prevent user from submittin with enter key:
if (e.which == 13) {
e.preventDefault();
}
i got the answer. it should put in the input tag which we want.
onkeydown='if ((event.keyCode == 13 && document.getElementById("field_0").value!="") && event.which == 13){
document.getElementById("field_1").focus();
event.preventDefault();
}'
I have to prevent the form submit if the newVal and oldVal are equal. Else I need to execute the Javascript function. - While pressing Enter key from the key board for the dynamically generated textboxes.
For this case, While pressing enter key the alert is coming repeatedly.
ie, first time one alert. Two alerts for second time.And the expected result is not getting.
What is expected: If I enter a value equals to the curValue then form doesn't have to submit.Else need to call the function myFun(); What is wrong with me?
function pressEnter(id,newValue,i)
{
var newId = '#'+id;
$(newId).keydown(function(event) {
var curValue= '<%=currentVal%>';
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert(newValue+"-"+curValue);
if(newValue== curValue)
{
event.preventDefault();
}
else
{
myFun(i);
}
}
});
}
You have to unbind previous keydown handler:
$(newId).off('keydown').keydown(function(event) {...});
You can do this comparison on form submit event rather than pressing enter key. Because user can use mouse and click the submit button.
Restrict user on form submit as follows,
$("#your_form_id").submit(function() {
var newValue = $(".your_textbox").val();
var curValue= '<%=currentVal%>';
if(newValue== curValue)
{
event.preventDefault();
//Or use return false;
} else{
myFun();
}
});
Here, we can avoid unwanted bind and unbind operations.
And we can achieve this on enter press, just write without function as follows,
$("#your_text_box_id").keydown(function(event) {
var newValue = $(".your_textbox").val();
var curValue= '<%=currentVal%>';
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert(newValue+"-"+curValue);
if(newValue== curValue)
{
event.preventDefault();
}else{
myFun();
}
}
});
Note: If you scope this jQuery code within a function,then javascript add handler for same event on every function call. Result is your code(Code in "keydown" callback) run multiple time. To avoid you have to unbind the event.
I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.
disableEnterKey: function disableEnterKey(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
},
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:
<script type="text/javascript">
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 code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".
Here are some highlights:
It is in pure javascript (no library required).
Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
Together with the above, user can use "Enter" key anywhere else.
It is short, clean, fast and straight to the point.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
In your form tag just paste this:
onkeypress="return event.keyCode != 13;"
Example
<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">
This can be useful if you want to do search when typing and ignoring ENTER.
/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)
AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.
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.
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.)
https://www.w3.org/TR/html5/forms.html#implicit-submission
However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.
So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).
The solution is so simple:
Replace type "Submit" with button
<input type="button" value="Submit" onclick="this.form.submit()" />
this is in pure javascript
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
});
Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:
//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
if (e.which == 13) e.preventDefault();
});
Thanks to this answer: https://stackoverflow.com/a/1977126/560114.
Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.
<script type="text/javascript">
function stopEnterKey(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 = stopEnterKey;
</script>
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form.
You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
I think setting a class to a form is much better. so I coded that:
HTML
<form class="submit-disabled">
JS
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('submit', function (e) {
e.preventDefault()
});
/**
* </End>
* Submit Disabled Form
*/
And also if you want to disable submitting only when Enter Key press:
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
e.preventDefault()
}
});
/**
* </End>
* Submit Disabled Form
*/
in HTML file:
#keypress="disableEnterKey($event)"
in js file:
disableEnterKey(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
}
First you need to disable the form on submit, but re-enable it when clicked on the button. which or keycode is not used in this case, avoiding some problems with compatibility.
let formExample = document.getElementbyId("formExample");//selects the form
formExample.addEventListener("submit", function(event){ //must be used "submit"
event.preventDefault();// prevents "form" from being sent
})
To reactivate and submit the form by clicking the button:
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateButton); //calls the function "activateButton()" on click
function activateButton(){
formExample.submit(); //submits the form
}
a variation of this would be
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateBtnConditions); //calls the function "activateBtnConditions()" on click
function activateBtnConditions(){
if(condition){
instruction
}
else{
formExample.submit()
}
}
Here is a modern, simple and reactive solution which works in:
React, Solidjs, JSX etc.
is written in Typescript
supports server-side rendering (SSR)
all modern browsers
does NOT require jQuery
blocks ALL Enter keys outside of <textarea> where you want to allow Enter
// avoids accidential form submission, add via event listener
function blockEnterKey(e: KeyboardEvent) {
if (e.key == "Enter" && !(e.target instanceof HTMLTextAreaElement)) {
e.preventDefault()
}
}
// add the event listener before the rendering return in React, etc.
if (typeof window !== undefined) {
window.addEventListener("keydown", blockEnterKey)
// the following line is for Solidjs. React has similar cleanup functionality
// onCleanup(() => document.body.removeEventListener("keydown", blockEnterKey))
}
return(
<form>
...
</form>
)
The better way I found here:
Dream.In.Code
action="javascript: void(0)" or action="return false;" (doesn't work on me)