Reputation: 161
I am trying to disable submitting a form when the user presses enter on input fields, but I can't seem to get anything to work. The latest script I've tried was adding this to the head:
<script type="text/javascript">
$(document).ready(function() {
$(window).keydown(function(event){
if(event.target.tagName != 'INPUT') {
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
}
});
});
</script>
I am not receiving any errors in the console so I can't tell if something is conflicting.
Upvotes: 0
Views: 551
Reputation: 1370
You can use event capturing for that.
window.addEventListener('keydown',function(event) {
if(event.target.tagName != 'INPUT') {
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
}
}, true);
Upvotes: 0
Reputation: 3435
Right now you're capturing the event in the window, so preventDefault()
isn't going to do what you want it to. you need to capture it from the form so you can prevent its default submit action
Try:
$('form').on('keyup keypress', function(e) {
var keyCode = e.keyCode;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
Upvotes: 3