Simulating a click to submit a form in jQuery - javascript

Alright so I have a text field that will have a bar code scanned into said text field. It will search the database and return information in the form of a submit button. I am using this code to simulate a click on the submit button.
if($.browser.msie){
//simulate a click on the button
$("#search").keyup(function (e) {
if(e.keyCode == 13) {
$('input:submit').click();
}
});
}
The problem with this code is that it takes all of the keystrokes and then clicks the button that many times. This submit will represent data that gets written into the database, so if the bar code was abc123 it would do this action 6 times, but I just need it to do it once. How do I fix this? My code works in FF and Chrome, but not IE, which is the one I need to get this to work in. Grrr I hate IE so much!

Why do you need to "click" that submit button? Why don't you just submit the form like:
$("#search").blur(function(){
document.myform.submit();
});
Your barcode reader will do this for you.

Try to get code like this:
var keyCode = (window.event) ? e.which : e.keyCode;

Related

Prevent form submit on enter VueJS/Semantic UI

Have been searching for a solution to this problem for 2 days now and none of the suggested solutions have worked so far.
My form html is defined with
<form id="quote_form" action="" method="get" class="ui large form">
and input text fields in the form
<input v-model="city" type="text" name="quote[city]" id="city">
I have been trying to isolate the cause of the issue but have not been able to do so. I tried turning off the keyboard shortcuts settings for semantic ui forms:
$('.ui.form').form({
keyboardShortcuts: false
});
I have also tried to override the enter key and prevent it from triggering the submit function in these ways:
$('#quote_form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.stopPropagation();
e.preventDefault();
return false;
}
});
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
$('#quote_form').bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});
The form has multiple steps in filling it in. Each step uses a button to permit the advance to the next step. When enter is pressed then it causes the form to redirect to the first step/tab of the form. The only case where it doesn't redirect is when the rules of the current step are not satisfied. The form submission is handled by a submit button where the button itself calls methods to validate and submit the form. I can't find any connection between enter submit behaviour and the button for submitting.
If I am missing any useful information to help isolate the cause then please let me know. I'm new to asking questions here and want to prevent my question from being considered bad as much as possible :)
Here is solution for you:
#submit.prevent
https://jsfiddle.net/4qpffycs/2/
Just use #keyup.enter.prevent at the end of the input markup. See VueJS Doc
By the way, you should try to use native VueJS Events instead of all redoing it with JQuery
The solution I found regards only Semantic UI without VueJS, but should be applicable here and gives a bit of an insight into the issue.
The problem arises from the fact that $("#formId").form({ ... }) registers an event handler for a button press and submitting the form on Enter press if one of the input boxes are selected. This can be seen in Chrome DevTools when selecting the element and choosing Event Listeners category:
The simplest way I found to remove this behavior is to call
$("#formId").unbind('keydown')
to remove the keydown bind completely from the element.

JavaScript & submit form & Enter & set focus to next element

I'm trying to create a simple submit form in WYSIWYG Web Designer 10 but I have a BIG problem with Enter key. There are several edit boxes on the form and I'd like to have the following functionality (via JavaScript):
1. Enter key on an Edit Box should not submit the form.
2. Enter key on an Edit Box should set focus to the following element (edit box or a submit button). Submit button is the last element in tabIndex order.
3. To submit the form user must:
either click the submit button,
or press Enter when the submit button has the focus.
4. Must work in any browser.
This is a snippet that works quite good (it sets focus to the next element):
var elem = document.activeElement;
var tidx = +(elem.getAttribute('tabindex')) +1,
elems = document.getElementsByTagName('input');
for (var i=elems.length; i--;)
{
var tidx2 = elems[i].getAttribute('tabindex');
if (tidx2 == tidx) elems[i].focus();
}
The only problem I have is Enter key (keyCode) validation which should precede the code to change focus. I have been testing in FF 32, PaleMoon 25 (FF clone), Chrome 38 & IE 10.
Thank you very much for your time in advance.
P.S. I'm a newbie in JavaScript. I use to work with MS Access where similar problem would be solved within two minutes.
I have spent several hours on this simple task but no luck. I have tried many examples that I've found on the web (incl. stackoverflow.com). As to event handling (where I'm trying to test the keyCode) various browsers behave differently.
I tried and mixed a lot of found in web and created this one.
So far it's working for me... just give it a try
$(document).on('keypress', 'input, select, checkbox, radio, button', function (e) {
return focusNextOnEnter(e, this);
})
and the function somewhere in your JS file.
function focusNextOnEnter(e, selector) {
var longSelector = 'input:visible:enabled:not([readonly="readonly"]), textarea:visible:enabled:not([readonly="readonly"]), select:visible:enabled, button:visible:enabled';
var keyCode = e.keyCode || e.which;
if ($(selector).is(':not(textarea)') // it's not a textarea - enter in text area
&& keyCode === 13 // it's enter key
&& !($(selector).attr('id') === 'submitButton')) // it's not submitButton, save-on-enter here
{
e.preventDefault();
$(longSelector)[$(longSelector).index($(selector)) + 1].focus();
return true;
}
}
instead of the last check
$(selector).attr('id') === 'submitButton'
you can always check
$(selector).is('[type="submit"]')
this will hopefully return what you are looking for i.e. submit on enter on submit button

Map enter key to submit while not inside input

I have a form with multiple input boxes that I'm trying to get to submit when I press the enter key, regardless of whether or not one of the inputs is currently highlighted. That is, I want to be able to enter text, click the background of the page, hit enter, and have the form submitted. I have tried making a hidden button, but this solution only appears to submit when the cursor is inside one of the inputs.
Use onkeypress on document using pure javascript:
Fiddle.(demo)
JS:
var form = document.getElementById('form');
document.onkeypress = function(e) {
if(e.keyCode === 13) //if enter pressed
{
form.submit();
}
}
Here's another solution using addEventListener, as suggested by Matt:
var form = document.getElementById('form');
function submitForm(e) {
if(e.keyCode === 13) //if enter pressed
{
form.submit();
}
}
document.addEventListener('keypress', function() {submitForm(event)}, false);
As a side note:
I would discourage you using jQuery on places where pure JS can help you easily that's why gave you a javascript solution. I would discourage that because jQuery increases the load on the server alot!
As you said you are new to javascript do the following steps to get your script running everytime:
Add my code to a file with .js extension
Add <script src="your_filename.js" type="text/javascript"></script> before your closing </body> tag.
Refresh your page and voila.
With the help of jQuery:
$(document).keydown(function(e) {
if (e.keyCode == 13) {
$('#your-form').submit();
return false;
}
});

Form submitted twice using submit() on keyup

I had a jQuery / HTML code similar to this:
<form action="/SomeAction" method="post">
<input id="my-textbox" type="text" placeholder="Write something and press enter to continue..." />
</form>
<script type="text/javascript">
$(function() {
$('#my-textbox').keyup(function(e) {
var $textbox = $(this);
if ($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
}
});
});
</script>
The purpose was to automatically submit the form when the user pressed the Enter key. I regularly use Firefox so everything was OK for me until I tested in Google Chrome and Internet Explorer.
When I pressed the Enter key in the later browsers, sometimes I would get the form submitted twice. This was easy to notice because I would get duplicate entries in my DB and I'd see two POSTs using Fiddler.
After some testing, I found out that my problem was the jQuery code, since the textbox would submit automatically on enter without it, and using this code would produce a second POST in some browsers.
My questions are:
Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?
Should I expect this behavior in all major browsers in all platforms?
Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?
Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?
That is the default behavior. What if you didn't have your script and the default behavior was such that the form wouldn't POST on enter.
Should I expect this behavior in all major browsers in all platforms?
Yes
Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?
Use a global mutex variable and set it once the form POSTs - checking it on subsequent POSTs to validate. Or, return false from the keyup handler and stop the event propagation.
Some browsers will interpret an input button as a submit if there is only one button in the form. Just return false in your function to prevent the default behavior from submitting the form.
if ($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
return false;
}
Your form is being submitted right after the enter has been pressed (on keydown and before keyup fires) so you can do
$(function() {
$('#my-textbox').keydown(function(e){
if(e.keyCode==13) e.preventDefault();
});
$('#my-textbox').keyup(function(e) {
e.preventDefault();
var $textbox = $(this);
if($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
}
});
});​
A simple test.
Add boolean variable that would be set to true after first submit and use that variable in your if condition. This would prevent accidental double click.
You should also prevent double submit in the application backend (many web frameworks have built-in mechanism for doing this, it easy to come up with custom solution as well).

trouble catching enter keystroke in javascript

this seems simple, but i can't make it work.
i'm trying to catch an enter keystroke, and run some code, but when i hit enter, the page refreshes and nothing happens.
here's my script
function GetChar(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
if (keyCode == '13') {
var cQuery = document.getElementById('searchfield').value;
var cURL = 'ProductGrid.aspx?Query=' + escape(cQuery);
document.location = cURL;
};
wheni hit enter the page is refreshed, and the search field is cleared, but it doesn't run any of the code in the if block
If your searchfield is inside a Form, this Form gets submitted, causing your code not to run.
You can either remove the Form and just use the Input-field, or you have to stop the Form-Submit by using somehting like this:
<form onSubmit="this.preventDefault&&this.preventDefault();this.returnValue=false;return false;">
Are you using keypress event? Explorer doesn't fire the keypress event for Enter...
http://www.quirksmode.org/js/keys.html
Returning false from your function could do the job.

Categories