How to disable Enter key from pressing buttons? - javascript

I currently have a button with an onclick attribute, directing to a JS function.
After I click it with my mouse, pressing the Enter key clicks the button as well, which I want to disable.
My button:
<button onclick = "action()">Button</button>
My JS function:
function action(){
//do something
}
I tried solutions from Disable Enter Key and Disabling enter key for form, but they don't work.
How do I solve this? Should I not use onclick? I would like a solution in pure JS.

You could have an event listener listening for a keydown event and check if it's the enter key and the target your button. In that case disable the event.
Something like this should work, you can add the correct type:
window.addEventListener('keydown',(e) => {
if (e.keyIdentifier =='U+000A' || e.keyIdentifier =='Enter' || e.keyCode == 13)
if (e.target.nodeName=='BUTTON' && e.target.type=='') {
e.preventDefault()
e.stopPropagation()
return false
}
}, true);

try setting the button to .blur() or set focus to another element
<button onclick = "action();">Click this</button>
function action(){
//do something
this.blur()
}

Related

Submit button fires twice

I have the following submit:
<input type="submit" id="buttonNext" name="buttoncrd" value="Prosegui" class="buttonNavProsegui block-ui"/>
When you are on the page, i want to active the submit with the keyboard button "Entry" so i made this simple js code:
$(document).ready(function() {
$(document).keypress(function(event){
if (event.which == 13){
$("#buttonNext").click();
}
});
});
It works correctly but i met some problem when i have the focus on the submit AND i press Enter on the keyboard. I fear that the submit fires twice, can you help me disable one submit when is focused?
You can use
$(document).ready(function() {
$(document).keypress(function(event){
if (event.which == 13){
$("#buttonNext").click();
event.preventDefault();
}
});
});
It will not trigger twice.
$("#buttonNext").addEventListener('keypress', e => {
e.stopPropagation()
})
might do the trick. It prevents the event from propagating up in the hierarchy when a keypress event happens on the button.

form should not submit on enter if focus is not on submit button

I have a requirement where user cannot submit the form if he press enter key unless focus will be on submit button.
Using following code, I am able to do that, but now the issue is, if I have any enter key event attached specific to any field (e.g. if I want to attach enter key event to one textfield for some special requirement), it is not allowing me due to the script I have written below..
<script>
$(document).keydown(function(event) {
if (event.keyCode == 13) {
var $focusedItem = $(document.activeElement);
if($focusedItem.is("button") || $focusedItem.is("a") || $focusedItem.attr("type") == "submit") {
$focusedItem.click();
}
else {
event.preventDefault();
}
}
});
</script>
Any solution where I can restrict user from submitting form on pressing enter key, if focus is not on the submit button but at the same time if there will be any enter key event attached to any form-field, that should also work.
If you had created a JsFiddle it would be easier to help. However, I'm thinking you should do something like this:
if($focusedItem.attr('id') == 'submitButton') {
if (event.keyCode == 13) {
submit the form
}
}else if ($focusedItem.attr('id') == 'Anothertextarea') {
if (event.keyCode == 13) {
do something special
}
}else{
if (event.keyCode == 13) {
return null;
}
}
Remove the line event.stopPropagation(); from your script, you need only the preventDefault() (prevents the submit).
When you do stopPropagation() you are stopping all other keypress events on the element.
Try that and see if it fits your needs:
--DEMO--
$(document).on('submit', 'form', function (e) {
e.preventDefault();
}).on('click', ':submit', function (e) {
if (!$(document.activeElement).is(':submit')) return;
var form = $(this).closest('form').length ? $(this).closest('form')[0] : $('#' + $(this).attr('form'))[0];
form.submit();
});
Maybe I'm missing the point, this is basically a standard html issue.
Don't give the form an submit action (move it to a click event directly on the button) and change all button types to button instead of submit.
I can't remember if simply removing the submit from the form is enough. If not then just do onSubmit="return false;" I think that does it.
However as a note the requirement for this as a global behavior is probably wrong and if its for the government then you will probably get in trouble since its not compliant with accessibility guidelines.

Press the enter key in a text box with jQuery

How can I mimic pressing the enter button from within a <input>, using jQuery?
In other words, when a <input> (type text) is in focus and you press enter, a certain event is triggered. How can I trigger that event with jQuery?
There is no form being submitted, so .submit() won't work
EDIT
Okay, please listen carefully, because my question is being misinterpreted. I do NOT want to trigger events WHEN the enter button is pressed in textbox. I want to simulate the enter button being pressed inside the textbox, and trigger this from jQuery, from $(document).ready. So no method involving on.('keypress')... or stuff like that is what I'm looking for.
Use keypress then check the keycode
Try this
$('input').on('keypress', function(e) {
var code = e.keyCode || e.which;
if(code==13){
// Enter pressed... do anything here...
}
});
OR
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
DEMO
Try this:
$('input').trigger(
jQuery.Event('keydown', { which: 13 })
);
try using .trigger() .Docs are here
Instead of using {which:13} try using {keyCode:13}.
$('input').trigger(jQuery.Event('keydown', {keyCode:13}));

onkeypress on a <a> tag

I'm trying get my <a> tag triggered when the user press on the "enter" key. (onkeypress).
my <a> tag:
<a href="javascript:search()" onkeypress="return runScript(event)">
this is my javascript :
function runScript(e)
{
if (e.keyCode == 13) {
alert("dssd");
return false;
}
}
I dont know whats messed up ?
its work for me
Open in new window using javascript
javaScript
window.runScript = function (e) {
if (e.keyCode == 13) {
alert('ss');
return false;
}
else {
return true;
}
}
window.search = function () {
alert('s');
}
live demo : fiddle
Write your html as given below. Note the property tabindex which makes the a tag focusable in certain browsers.
<a id="link" href="http://google.com" onkeydown="runScript(event)" tabindex="1">I am a link</a>
If you need an autofocus on load, you can use the jQuery function focus as shown below.
$(document).ready(
function(e){
$("#link").focus();
}
);
Then your function
function runScript(e){
if(e.keyCode == 13){
alert("pressed enter key");
}
}
you have to call e.preventDefault(); (or return false in some browsers) if you want to prevent the link load the link in href.
function runScript(e){
e.preventDefault();
if(e.keyCode == 13){
alert("pressed enter key");
}
return false;
}
see a demo here:
http://jsfiddle.net/diode/hfJSn/9/show press enter key when the page is loaded
The ENTER key actually triggers the onclick event:
<a href="#" onclick="alert('hello!');">
This means that your search() function inside the href will execute before the onkeypress event.
That works in my browser, though I suspect it's not the way to achieve what you actually want to do... (maybe?)
Number one, you probably don't want it to "return" anything, so you can just do onkeypress="runScript(e)" and it'll run. If that function does return a value, it's not gonna go anywhere...
Number two, it's kinda rare that a keydown event would fire on an anchor (<a>) element, unless of course the user tabs through the other elements 'till it has focus and then presses a key (usually the browser will "highlight" the element that currently has keyboard focus, if it's not just the whole page). Are you wanting your script to run when someone presses enter after typing in a search box or something? if so, you probably want to listen for the event on the search box itself, so add it as that element's onkeydown attribute (for example: <input id="mySearchBox" onkeydown="runScript(e)">) if you just want it to run whenever the user presses enter, regardless of focus or typing text into any particular field, just do as edmastermind29's comment said and add the event listener to the whole document.
Have you tried adding this to your script?
document.onkeypress = runScript;

enter in asp:TextBox clicks my button (which has a js function bound to it)

basically I have this:
<asp:TextBox runat='server' />
<button id='b2'>hi</button>
<script>
$('#b2').click(function(e){
e.preventDefault();
alert('you clicked the button');
});
</script>
the problem is that when hitting enter inside the textbox the click event on the b2 occurs so I get the js function executed, anybody knows how to stop this?
Pressing the return/enter key while focusing a text box is treated the same way as clicking on the submit button. What you can do is attach a keypress event handler to all text boxes in your form, and simply ignore the return key press.
Code looks like this:
$('input[type="text"]').keypress(function(event) {
if(event.keyCode == 13) {
event.preventDefault();
alert("enter!");
}
});
Note that I don't use ASP, so I tested this with a standard HTML text box and submit button.
adding the attribute type="button" to the button tag stopped this behavior o_O

Categories

Resources