Reputation: 5143
I noticed that if you focus on an element that mouse clic can be triggered, the Enter keys acts like as you left click the mouse. I want to avoid this running since it comes into conflict in other pieces of my code.
In the following example if I focus on this imageButton and I clic once, the next clicks can be "done" with the Enter key, so I don't want this because this button fires a slideToggle() and shows a hidden div, so IMO it's pointless toggle this div with the keyboard.
Is there any way to make it global way? Thank you.
Upvotes: 5
Views: 2329
Reputation: 337560
To address this you can call preventDefault()
on the event that's raised. You can detect the key that was pressed, and if it was the Return key, cancel its default behaviour. Try this:
$(".myElements").on('keypress', e => {
if (e.key == 'Enter') {
e.preventDefault();
console.log('Enter key was pressed');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input class="myElements" />
Upvotes: 4
Reputation: 5475
try this code
$('body *').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
}
});
the above code will prevent pressing enter for every element in page
,You can change the selector $('body *')
to something else depending to your case
Upvotes: 0
Reputation: 74420
An other possible way i think:
$('.elems').on('click',function(){$(this).blur()});
Upvotes: 0
Reputation: 66304
Listen for "keypress"
and .preventDefault()
ex. with <myelm class="nokey"/>
function noKeyPressing(){
var elms = document.getElementsByClassName('nokey'),
stop = function stop(e){ return e.preventDefault(), false; },
i = elms.length;
while(--i >= 0){
elms[i].addEventListener('keypress', stop, true);
}
}
noKeyPressing()
If you just want to prevent Enter then the keyCode to look for is 13.
Upvotes: 1
Reputation: 12683
You can return false to prevent the default action.
<input type="submit" onkeypress="return false;" value="Submit" />
Upvotes: 0