mardi 31 mars 2015

Prevent user hitting Enter except Textarea

I have a fairly complex form which has multiple stages with many different text fields and text areas. The environment it is used within used barcodes which hit enter by default, and that is by choice as they scan a multitude of products using them so turning the enter function off has become a no-go.


I am using a form wizard script which handles client-side validation during the input stage. This script is interrupted by the enter key being hit during filling out the form and refuses to submit until the page is refreshed.



<a href="javascript:;" class="btn green button-submit">Submit <i class="m-icon-swapright m-icon-white"></i></a>


I have the following code which works to prevent enter on the form and allows the form to submit when the link above is clicked.



$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});


However this prevents enter being used within textarea, as such I did a bit of research and tried using the is() operator from jQuery



$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13 && !event.is("textarea")) {
event.preventDefault();
return false;
}
});
});


This doesn't work, it fails to prevent the enter key in inputs and stalls the form from submitting as it did prior.


Finally this is the javascript that handles submitting the form if validation passes on the form



$('#form_wizard_1 .button-submit').click(function () {
// Can put more onsubmit processing here
document.getElementById('submit_form').submit();
}).hide();




Can anyone suggest how I can prevent the enter key on all inputs EXCEPT for textareas. I don't pretend to be a JavaScript developer, although I am trying to learn as I go. The following are articles I have read and either attempted to adapt code or failed to understand how it would apply to me in the correct manner;


Prevent Users from submitting form by hitting enter


Prevent Users from submitting form by hitting enter #2


disable enter key on page, but NOT in textarea




*In regards to the last link, I need a global resolution that automatically prevents it on all textareas that may exist within the form.


As always, thank you for your assistance.


Aucun commentaire:

Enregistrer un commentaire