I have an input element with onchange="do_something()". When I am typing and hit the enter key it executes correctly (do_something first, submit then) on Firefox and Chromium (not tested in IE and Safari), however in Opera it doesn't (it submits immediately). I tried using a delay like this:
<form action="." method="POST" onsubmit="wait_using_a_big_loop()">
<input type="text" onchange="do_something()">
</form>
but it didn't work either.
Do you have some recommendations?
Edit:
Finally I used a mix of the solutions provided by iftrue and crescentfresh, just unfocus the field to fire do_something() method, I did this because some other input fields had others methods onchange.
$('#myForm').submit( function(){
$('#id_submit').focus();
} );
Thanks
You could use jquery and hijack the form.
http://docs.jquery.com/Events/submit
<form id = "myForm">
</form>
$('#myForm').submit( function(){
do_something();
} );
This should submit the form after calling that method. If you need more fine-grained control, throw a return false at the end of the submit event and make your own post request with $.post();
From http://cross-browser.com/forums/viewtopic.php?id=123:
Per the spec, pressing enter is not
supposed to fire the change event. The
change event occurs when a control
loses focus and its value has changed.
In IE pressing enter focuses the
submit button - so the text input
loses focus and this causes a change
event.
In FF pressing enter does not focus
the submit button, yet the change
event still occurs.
In Opera neither of the above occurs.
keydown is more consistent across browsers for detecting changes in a field.
I'm not great at Javascript, but could you do something like this?
<form name="myform" action="." method="POST">
<input type="text" onchange="do_something();document.myform.submit();">
</form>
Related
Hello Stackoverflow!
I am experimenting with getting a chrome extensions cript to click a page button to trigger an AJAX request, however it would seem that physically clicking said button is not the same as using the following:
document.getElementsByTagName('input')[10].click();
the results of the getElements line is this:
<input type="submit" value="Continue ...">
Using document.forms sort of works, but unfortunately reloads the page, which is not what happens when the Ajaxrequest is fired by the click event.
document.forms[1].submit();
Calling the form returns the following:
<form
action="/battle.php" method="post" name="2913" id="2913" onsubmit="get('/battle.php', '', this);
disableSubmitButton(this);
return false;">…</form>
Doesn't seem obvious to a beginner programmer like me, why using the .click(); in F12 console (chrome) would be any different from the physical click. Also i have verified (sorf of) that the button on the screen is in fact the one i'm calling with the getElementsByTagName('input').
The page reloads because the type of the button is "submit". You could attach an event handler to the "click" button that can submit the form without reloading the page. Your code will look something like this:
Using JQuery:
$('#submitButton').on('click', function(e){
e.preventDefault(); // stops default submit
$('#2913').submit(); // or the ID of your form
});
And your HTML will be :
<input type="button" value="Continue ..." id="submitButton">
All I find when I google this is the opposite.
I have this jquery for disabling form buttons after they were clicked once.
$('.btn').click(function (event) {
$(event.target).prop("disabled", true);
});
In Firefox (after adding autocomplete="off" because of this "feature") and IE this works as intended, the button is disabled but the form action is also performed, restricting the user form clicking it more than once. However in Chrome it stops the event propagation by itself, and I cannot find how to make it not do that.
You can force the form submission like that:
$(event.target).prop("disabled", true).closest("form").trigger("submit");
When you have more than one submit button in a form, is there a way to know which one fired the onsubmit event without adding code to the buttons themselves?
Edit: I need to do the check on the client-side, i.e. with JavaScript.
The "submit" event is not fired by the button, but its fired by the "form". A quick test proves this:
<form id="myform">
<input id="email" type="text" value="1st Email" />
<input id="action1" type="submit" value="Action 1" />
<input id="action2" type="submit" value="Action 2" />
</form>
<script type="text/javascript">
document.getElementById("myform").onsubmit = function(evt) {
var event = evt || window.event;
alert(event.target.id); // myform
alert(event.explicitOriginalTarget.id); // action2 (if action2 was clicked)
// but only works in firefox!
}
</script>
Although in firefox, you can use event.explicitOriginalTarget property on event to get the input (submit) that was clicked causing the submit event to be fired. (if you want to know)
So best options for you are:
Have a different value to your submit buttons OR
Have those as normal buttons and click handlers to them via javascript.
There is a submitter attribute on SubmitEvent object.
See example:
<!DOCTYPE html>
<html>
<body>
<form action="./test.html" onsubmit="myFunction(event)">
Enter name: <input type="text" name="fname">
<button id="firstButton" type="submit">Button 1</button>
<button id="secondButton" type="submit">Button 2</button>
</form>
<script>
function myFunction(event) {
// This should log id of the button that was used for submition
console.log(event.submitter.id);
// Prevent sending the form (just for testing)
event.preventDefault();
}
</script>
</body>
</html>
See https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter
Does having an event listener on each button count as adding code? Otherwise, there's no way to see what button triggered the submit event, unless you want to get down and dirty and calculate the mouse position during the event and compare it to button positions.
Otherwise, the next best thing would be to assign an event handler for the click event of button and assign the name of that button to a variable you can check in the form's submit event.
There are a couple of ways that I can think of.
You can use different values, and your unobtrusive javascript can help with it.
One discussion on this approach (using different values for each button) is here:
http://www.chami.com/tips/internet/042599I.html
I tend to go with using different name attributes for each button.
A blog on that is here: http://www.codetoad.com/javascript/multiple.asp
I don't follow either of these, which approach will work best is going to depend on different factors, such as, are you handling the submit buttons in javascript, or will the server get the form, then have to figure out what the user wanted.
Personally, I prefer to use the ajax approach, now, where I just attach events to the buttons after the page is loaded, using unobtrusive javascript, and then based on the user choice call out to the correct function, but that depends on whether you can add a script link to the html page.
UPDATE:
In order to do this with javascript, the simplest way is to attach an event on the click of the button, and then look at the name to decide how to handle it.
In actuality, the form never truly has to be submitted to the server, but you can handle everything in the background by wrapping up the parameters (options) and sending them to the server, and let the user know the results.
Sorry to warm up this very old thread. The question hadn't been answered here but only approaches for practical workarounds have been given here before.
But the event-object does carry information about which object has initiated it. In a handler b4submit(e) you can get the submit-button like this:
function b4submit(e) {
var but = e.originalEvent.explicitOriginalTarget;
...
}
And but is an HTML Object with all the attributes you've assigned it with, like name, id, value etc.
I came across this after some debugging, and I thought it might be of a wider interest as a clean solution for this issue.
For me the simplest option that worked for me is to use document.activeElement if you want to get the id use document.activeElement.id if you want to get the text content you can simply put document.activeElement.textContent
const onSubmit = () => {
console.log('document.activeElement', document.activeElement.id)
if (document.activeElement.textContent === 'Suivant') {
handleNext()
return
}
if (document.activeElement.textContent === 'Confirmer') {
console.log('Payer')
return
}
}
I have a form where I've specified onSubmit="validate()", but I want to ignore the validation if the submit-button was clicked. Is there a good cross-browser way of detecting if the submit button was clicked and thus ignoring the validation?
Why don't you use a button instead of a submit, and set it's action on the click of the button? That way you can control if you want to validate, submit, or whatever else you like.
The submit event only fires if the form is submitted by the user; not if it is submitted via JS.
Therefore:
<input type="submit" onclick="this.form.submit(); return false;">
If JS is not available, this acts like a normal submit button … and the onsubmit still fails to fire as it also requires JS.
(Attaching events using JS instead of intrinsic event attributes is, as usual, preferred by excluded from this example for the sake of clarity)
you can try to use a <input type="button"... with an onClick that submits the form - a javascript .submit() doesn't fire the onSubmit-function of the form.
Did you try this?
<input type="submit" onclick="void(window.validate=function(){return true;})" value="Submit" />
Just return false, or preventDefault from your submit button handler
Consider an HTML form:
<form action="" method="POST" onsubmit="return checkValidArray()">
<input type="text" name="data" onchange="return validate(this);">
</form>
It appears (in both IE 6 and Firefox 3) that when you type some text into the input field and click submit that the onchange event fires for the input field, but the onsubmit event does not fire for the form until you click the submit button a second time (at which time the onchange does not fire, of course). In other words, the onchange seems to prevent the onsubmit from firing.
The desire is to check each field in the form when the user exits the field in order to provide them with immediate validation feedback, and also to prevent submission of the form if there is invalid data.
[EDIT: Note that both validation functions contain an alert().]
How does one get around this problem?
Solution (of a sort):
It turns out that it is only presence of an alert() - or a confirm() - during the input's onchange event that causes the form's onsubmit event to not fire. The JS thread appears to get blocked by the alert().
The workaround is to not include any alert() or confirm() in the input's onchange call.
Browsers known to be affected:
IE6 - Windows
IE8 - Win
FF3 - Win
Browsers known not to be affected:
Google Chrome - Win
Safari - Mac
FF - Mac
I tried with Firefox 3 (Mac) with the following code:
<html>
<head>
<script>
function validate(ele)
{
alert("vali");
return false;
}
function checkValidArray()
{
alert("checkValidArray");
}
</script>
</head>
<body>
<form action="" method="POST" onsubmit="return checkValidArray()">
<input type="text" name="data" onchange="return validate(this);">
<input type="submit" value="Ok">
</form>
</body>
</html>
It seems to work. When I click on the Ok button, both "Vali" and "Check Valid Array" pop up.
Initially I thought return false could be the reason why the form was not submitted, but it IS submitted (at least, checkValidArray() is called).
Now, what are you doing in your checkValidArray() and validate() methods? Something special? Can you post the code?
EDIT: I tested with IE8 and FF3 on windows, and here both events do not get fired. I have no idea why. Perhaps onblur IS a solution, but WHY does onchange not work? Is there a specific reason or is it just another inconsistency? (Works on both FF and Safari on Mac)
You could use the onblur event in your inputs instead of onchange.
It's quite interesting that the behaviour is different on the Mac, so it appears platform dependent and not browser dependent. Must be a clue there somewhere...
I tried onblur with Nivas' code but had the same result as with onchange (only the "Vali" alert).
What does make a difference is whether you do anything in validate(). Comment out the line alert("vali"); and it works! (The actual return value from validate() does not matter, although I wouldn't expect it to.)
EDIT:
A colleague just tried this in Google Chrome on Windows and it works there. This intuitively makes sense because of how Chrome separates JS threads.
Something about the first alert() blocking the thread causes the onsubmit event to get lost. Possible race condition?
Don't create ; submit button. Instead, create a normal button and write a function which can be called onClick with that button.
Function will do the validation on the form fields, and if everything is fine, it will submit the form. Otherwise it will not.
function validate
{
"Piece of code to Validate your form"
document.formName.action.value = "URL which you want to call"
document.propFile.submit(); // It will submit he page
}