How to run JavaScript code when a form is being reset? - javascript

I know we can attach a handler to the form onsubmit... But how can we add a handler to the form reset event? (usually when clicking on <input type="reset">)
Or... Maybe there is no such event... So the question becomes on how to work-around that?
(right now, I want to run a handler after the reset event; but someday I might need to run before the reset event)

According to MDN, the <form> tag supports an onreset event.
Onreset fires before the actual resetting of the form; there doesn't appear to be any event for after resetting. I tested to see if the reset would fire an onchange event for the inputs whose values are reset, but it does not appear to.
A workaround for doing something after resetting might be to set a flag on reset, and then use the onblur event of the reset button (so after you reset, it would run the next time you click on something else). An alternate workaround, of course, is to trigger a setTimeout so that your script would run a short time after the reset. Either one is a bit of a hack, I'm afraid.

found an answer to this that worked for me so I thought I'd post it for anyone else who came across this.
Instead of <input type='reset'>, you can use a <button> element with a click handler that first calls the form.reset() method, then you can add whatever scripting you need to happen after the reset action.

You can use the "reset" event of the "form" element
<form action="form_action.php" onreset="return confirm('Do you really want to reset the form?');">
....
</form>

Have you tried
<form onreset="action()">
Seems to work for me for running the script before resetting the form. As for after ... I don't think it's supported, possibly a setTimeout would do the trick.

Related

Clicking submit button using javascript and Firefox

I guess I have never tried to do this before ... I have a button on a page.
<input type="submit" id="btn" value="Submit">
And a javascript function that includes:
function clickit()
{
alert(document.getElementById('btn').value);
document.getElementById('btn').click();
}
Using Firefox, the button is not clicked - i.e. the form is not submitted. The alert shows, but the form does not get submitted. Why won't Firefox click a button?
Use a div or anything besides a INPUT element if you want to bind the click event to it. If <INPUT> is inside a form body, you might run into weird issues.
If you just need to submit a form with a button I would recommend that you just use a <div> element with a click handler rather than an input. It will give you a little more flexibility. If you do that then you should be able to just select your form and use the submit() API to submit the form.
If you really can't modify the code enough to do this and are having trouble selecting and submitting here is how you will need to do that using both jQuery and DOM.
The jQuery Way:
$("my selector").trigger("click")
You may run into issues around focus if you're running in PhantomJS or you've got a window like a test runner that is not in focus. In this case you can use:
$(<my selector>).triggerHandler(<my event>)
The DOM API way
This will just trigger the event (the equivalent of the first example)
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
You can also simulate a click with the actual DOM method
var button = document.getElementById('my-button');
button.click();
Why won't Firefox click a button?
I seem to recall that early versions of Firefox didn't allow calling of listeners that way for security reasons. However, I think those reasons have been addressed in other ways and now you should be able to call the click handler directly. The following submits the form in Firefox 34:
<form onsubmit="alert('submitted!!')">
<input name="foo" value="foo">
<input type="submit" id="aa">
</form>
<br>
<button onclick="document.getElementById('aa').click();">Click the submit button</button>
The form's submit listener is called and the form is submitted, so calling the submit button's click method is doing what it's supposed to.
This method doesn't work for all listeners though, click is a special case, see W3C DOM Level 3 Events Specification, ยง3.5 Activation triggers and behavior.

How to tell onBlur not to hide the submit button when clicked?

My blur event hides the submit button; but doing that seems to cancel the submit event. I only want to hide when the submit itself wasn't clicked. How can I determine if the focus was lost due to the submit, or due to just wandering off elsewhere?
<form action="" method="post">
<textarea id="message" name="message"></textarea>
<input type="submit" id="share" value="Share">
</form>
...
$('textarea').blur(function(){
$('#share').hide()
})
$('textarea').focus(function(){
$('#share').show()
})
Setting a timeout to allow the submit event to fire before coming back to the blur seems a bit hacky to me. Can't we do better than that? Can I tell the blur not to block other events? or search the dom for a pending submit event? or ... ?
Solution
for today is based on the ticked answer, but simpler. Use jquery's "fadeOut" routine to
delay the hidden status of the submit button until after the submit event has fired, and
make the user feel like their submission is being handled
.
$('textarea').blur(function(){
$('#share').fadeOut()
})
$('textarea').focus(function(){
$('#share').fadeIn()
})
It's indirect, and not really what I was looking for, but it seems clear that direct manipulation of the event queue - such as writing onBlur to say "if they did not click submit then hide the submit button" - is perhaps not technically possible.
This is one option, though a bit hacky using jQuery .queue() and .clearQueue() to set an animation queue and instantly clear it before anything happens:
$(function() {
$("#message").blur(function() {
$("#share").delay(100).fadeOut();
});
$("#share").click(function() {
$(this).clearQueue();
});
});
Note: Requires jQuery 1.4+
If you hide the Submit button, the submit will cancel.
Try making it completely transparent instead.
EDIT: For example:
$('#share').css({ opacity: 0, position: 'absolute' });

"onchange" event delayed in IE? (ok with Firefox)

It might be a beginner question but I can't understand why the onchange event is never called by IE while it works Ok with Firefox.
<input type="text" id="mytext" size="48" value="" onchange="execute()"/>
<button type="button" onclick="execute()">Go</button>
The execute function is called when the button is clicked but not when the text in the input box is changed.
Any idea?
IE only fires the onchange event when the element loses focus - if you were to click outside the element or tab to a different element it should fire then.
You can get around this by using a different event, for example onkeypress.
While annoying, it is not a bug that onchange is not fired until the element loses focus. (I get around the issue by having multiple bindings for different events; make sure not to clobber a handler and use an update aggregation if appropriate.)
Here is the "official" W3C documentation on the subject:
The onchange event occurs when a control loses the input focus and its value has been modified since gaining focus. This attribute applies to the following elements: INPUT, SELECT, and TEXTAREA.
Here is the MSDN reference:
This event is fired when the contents are committed and not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather [it is fired] when the user commits the change by leaving the text box that has focus.
The behavior, while often annoying, is as specified.
As answered elsewhere, IE doesn't fire the event till you click outside the input field.
Just a quick expaination of how I fixed it with jQuery. (This is a translation of my code, so it may contain bugs...)
<input id="somecheck" name="somecheck" value="1" onchange="dosomething();">
...was changed to...
<input id="somecheck" name="somecheck" value="1">
<script language="javascript">
$(document).ready(function() {
$('#somecheck').change(function() { dosomething(); } );
});
</script>
For those new to jQuery you are basically waiting for the page to become fully loaded, then you are adding the event handler 'dosomething' to the input box.
As far as i remember, IE doesn't handle onchange event the same maner as FF.
The event will be fired when the mouse is clicked.
I advise you to use a library to handle events such as jQuery, Dojo, etc..
ohhh, I spent some time on that issue as well months ago.
I came up with this solution for FF/IE onchange
$("input[name*='delivery_method']").bind(($.browser.msie ? "click" : "change"), function() {
//your code here
});
IE does it after your input loses focus, which isn't until you click the button, tab out, or click somewhere else on the screen. Try onclick or one of the other events.

javascript commands not all firing

I have a very simple JavaScript function:
function insertPost()
{
document.postsong.submit()
parent.document.getElementById('postSongButton').disabled = true;
}
Both commands in it work but only the first one will fire. This is true when they switch places also. Only the first one will fire...
document.postsong.submit()
Submits the form, takes focus away from the function, function ends there
parent.document.getElementById('postSongButton').disabled = true;
Disables the button, so perhaps it is that there is then nothing to submit the form.
Not too sure if disabling the form button would stop the event from bubbling, but I suspect that the nature of these two lines will lead you to separating them, and having the second one in another event handler.
Hope this points you in the right direction.
EDIT: On further inspection, I found that the real source of the problem is the line:
document.postsong.submit()
Here are the results of my tests in different browsers. If the line previous to the submit() is "button.disable = true", and the button type="submit":
Firefox disables the button and submits the form.
Chrome disables the button, but does not submit.
IE does not disable the button, but it does submit the form.
This explains the behavior you have been experiencing. Having parent before getElementById does not hurt anything, but it is not necessary. Change the code in your insertPost() function to this:
function insertPost(){
document.getElementById("postSongButton").disabled = true;
document.forms["postSong"].submit();
}
Did you check the casing of the html element?
on click of the button you are calling the funcion insertPost().so what you have to do first disabled the button and then submit the form.one think i didnt understand why are using parent of object.
function insertPost()
{
parent.document.getElementById('postSongButton').disabled = true;
document.postsong.submit();
}
You are using parent.document.getElementById(...
Just check if you are referring to the button correctly. i.e. if the parent reference you are using is correct. i.e if the button is in same page as the form or in the parent.
And yes, first you have to disable the button and then trigger the submit action for the form. When you do it the other way, you might end up navigating away to a different page and the disabling line may never execute.
But, since you said, disabling doesn't work for you at all, I thought if you were using wrong reference. Did it give any javascript errors for you when you tried to disable it?

Buttons OnClick event not firing when it causes a textboxes onChange event to fire first

I have a few textboxes and button to save their values on a web page. The onchange event of the textboxes fires some js which adds the changed text to a js array. The ok button when clicked flushes this to the database via a webservice. This works fine except when the onchange event is caused by clicking the ok button. In this scenario the onchange of the textboxes still fires but the onClick event of the button does not. Any ideas?
textboxes look something like:
<input name="ctrlJPView$tbcTabContainer$Details$JP_Details_Address2Text" type="text" value="test"
id="ctrlJPView_tbcTabContainer_Details_JP_Details_Address2Text" onchange="addSaveDetails('Jobs###' + document.getElementById('ctrlJPView_tbcTabContainer_Details_JP_Details_Address2Text').value + ');" style="font-size:8pt;Left:110px;Top:29px;Width:420px;Height:13px;Position:absolute;" />
My save button:
<input type="button" name="ctrlJPView$btnOk" value="OK" onclick="saveAmendments();refreshJobGrids();return false;__doPostBack('ctrlJPView$btnOk','')" id="ctrlJPView_btnOk" class="ControlText" style="width:60px;" />
UPDATE: I guess this comes down to one of two things.
Something is happening before the onClick of the button gets called to surpress that call such as an inadvertent return false; or
the onClick event isn't firing at all.
Now I've remembered out everything actually inside the functions that are being called beforehand but the problem persists, but if I remove the call altogether it works!
is the __doPostBack function the one failing to execute? in this case, the return false is the obvious problem - once you return, no more code gets executed.
on a more pedantic note, you should really stop using onBlah handlers in your html, and instead use a modern javascript library that provides event observers. i recommend jquery but extjs or prototype would also work and make life much easier for you in a thousand other ways.

Categories

Resources