JQUERY click handler from DIFFERENT element triggered on enter? - javascript

URL is here: http://prorankstudios.com/sandbox/wtf/
Using IE9, with focus on the User or Pass field, hit the ENTER key...
Notice that this whole page reloads.
What's happening is that the click handler for the #live_site_link (assigned on line 30 of common.js) is running when no click has happened on #live_site_link at all...
Login Submit code:
Login.Submit = function(e)
{
Login.feedback.empty();
if (Login.user.val() == '')
{
Camo.ErrorAlert('Invalid username.',Login.feedback);
Login.user.focus().select();
return false;
}
if (Login.pass.val() == '')
{
Camo.ErrorAlert('Invalid password.',Login.feedback);
Login.pass.focus().select();
return false;
}
Camo.AJAXStart('Logging in...');
postData =
{
user:Login.user.val(),
pass:Login.pass.val()
}
Camo.AJAXPost('index/login/',Login.Success,Login.Failure,postData);
return false;
}
live_site_link click handler:
$('#live_site_link').click(function()
{
window.location.href = './';
});
In fact, the handlers for the login form (both a keyup and a click on Go button assigned in login.js lines 22 and 24 respectively) sometimes run AFTER the page has reloaded, strangely enough.
In IE7/compatibility mode, the keyup and click handlers for login_submit properly work and the page does not reload. This is also the case in all other browsers I tested.
What is IE9 doing?

Try calling e.preventDefault() or e.stopPropagation() before you return false in Login.SubmitOnEnter
It would be better though if you wrapped a form around your form elements, then attached an event for the form submit. That way it will still work without javascript and you wouldn't have to have a separate event for click and enter press.

The only "fix" for this I could figure out short of changing the live site link button to a regular anchor tag was actually to enclose the login fields and button inside form tags.
Apparently without those enclosing form tags, IE9 is using the live_site_link button instead of the GO button to submit the form on a natural enter key press before the keyup handlers on the inputs and the click handler on the Go button of the login form ever get a chance to trigger, which causes the page to reload (as that's what the click handler for live_site_link does).
Now I have to handle logins without AJAX...

You would probably manage the login submittal process easier by using a submit handler rather than needing to catch enter key and make it click on submit button. Seems like extra code to work around doing it a simpler way
$('form').submit(function(){
var valid=someValidionFunction();
return valid;
})
Edited due to no ajax

Related

addEventListener not working || rearrange function firing sequence

I am placing my HTML form inside of another system and cannot get my own function to run during the submit event.
I cannot use Form onSubmit='foo' as the system has a script that automatically populates the onSubmit of any form placed inside of it (overwriting anything placed beforehand).
Additionally, this system has its own validation that it performs at the submit event.
So I am trying to use the EventListener to run my function as well as the system one at form submission, however it is not working. The console.log doesn't even show up.
I see that the system function has:
document.forms[0].submit();
So it must be firing before my function causing mine to never run as the system function either submits or cancels the submit it appears.
Here is my eventListener code.
var formRef = document.forms.myForm;
myForm.addEventListener('submit', function(evt) {
evt.preventDefault();
console.log('event fired');
//checkBlanks function loops through the form looking for blanks,
//if a field is blank it changes it to red and then fires the system's
//confirmation dialogue. Else it fires the system's confirmation dialogue.
checkBlanks();
});
In the event that it matters, my form is inside of the system's form and the submit button is located in the system's portion of the window. I tried to addEventListener the button but it says it cannot get property of undefined reference.
All you need to do is to call the form tag or you call an #id to it
enter code here
document.querySelector('form').addEventListener('submit',execute);
function execute(e){
console.log('submitting...');
e.preventDefault();
}

Link to anchor (ajax url) doesn't call onBeforeUnload

I have an onbeforeunload event :
$().ready(function() {
window.onbeforeunload=function() { return "haha" };
});
And my links are like this (ajax web site) :
<a href="#pageX" />
But the onbeforeunload is never called. What can i do ?
Thanks
I'm guessing since you're trying to bind to the onbeforeunload and return a string, that you're looking to provide the user with an "Are you sure you want to leave this page" dialog on an AJAX site.
In which case you probably need to go about this a little differently by binding a click handler onto the links. So you can prevent the hash change until the confirmation is made.
Something like:
$('a[href^="#"]').live('click',function(e){
if( //should we be confirming first? ) {
//put your confirmation code here either using default JS windows or your own CSS/jQueryUI dialog boxes
// this code should either cache the url of the link that was clicked and manually update the location with it when the user confirms the dialog box (if you're using JQUI windows) or simply use JS confirmation boxes and based on the response, all you need to do is return; and the link click will handle normally
e.preventDefault(); //prevent the link from changing the hash tag just yet
e.stopImmediatePropagation(); //prevent any parent elements from firing any events for this click
}
} );
Don't get me wrong, but are you serious ?
That link just refers a hash-tag, hence, it will not leave the current site and there will be no call to onbeforeunload nor unload.
If there is any *click event handlerbound to that anchor aswell, there must be something in the event handler code which really forces the current site to get unloaded (location.href` for instance).
If you just switch HTML via Ajax, there is no onbeforeunload aswell.
You could bind a handler to the onhashchange event (check browser compatibilty) but that would fire for any change that happens in your url/hash.
You're probably looking for the onhashchange event:
https://developer.mozilla.org/en/DOM/window.onhashchange

window.onbeforeunload: Is it possible to get any details about how the window was unloaded?

I'm developing one of those warning windows that tells the user that they may have unsaved data, but I only need it to warn them if they're leaving the page. Currently it does so on refreshes, postbacks, etc. I was wondering if there was any way to tell how the page was unloaded or otherwise get more details about what the user is doing to unload the page. (jquery solutions welcome).
Code for reference:
window.onbeforeunload = function () {
if (formIsDirty) {
formIsDirty = false;
return "Are you sure you want to navigate away from this page?";
}
}
on beforeunload event we can do below things:
We can pass event as a parameter to the function as in above answer.
Now we can use this event for available information attached to this
event.
And we can access Document level variables.
For example document.activeElement will give you the last element you clicked that caused the page unload.
Hope this helps!!
I think that the active element is not a valid solution.
I can't comment the "open and free" solution, I dont have reputation.
document.getActiveElement gets the currently focused element in the document. If a link have the focus and I press F5 or I close the tab the active element is the link.
Short answer: There's no easy way to find out what is causing onbeforeunload to fire.
Long answer: Inside your window.onbeforeunload handler you can access the window.event object, which may have some useful properties to determine how the window is closing.
For example, if window.event.srcElement is an anchor tag, then you know that the onbeforeunload event is firing by an anchor tag being clicked.
Refer to the event and onbeforeunload pages on MSDN for more properties.
Edit: some more info I have stumbled across -
If you want to ignore ASP controls that cause post-back, you can interrogate the '__EVENTTARGET' hidden input. If this input has a non-empty string value, then the page is being posted back by an ASP control.
You could also check the keyCode property (if F5 has been pressed, causing a refresh) or the mouse position to see if the X (close) button has been clicked.
I was running into a simular issue when a user was hitting enter from an input field on a form. The form was being submitted thus firing off the onbeforeunload event. I tried setting a flag to avoid showing the message on the keydown event on the input, filtering on the enterkey code. This wasn't getting triggered until after the onbeforeunload event was firing and therefore the flag wasn't getting set.
I then looked into the _EVENTTARGET as jbabey suggested. If the form was being submitted there would be a value in that field, if it was being refreshed there wouldn't.
Therefore, doing a simple check to see if there was value in the _EVENTARGET field in the onbeforeunload event could determine if the input from the form was causing the postback.
Here is my code.
window.onbeforeunload = function (e) {
if ($('[id$=__EVENTTARGET]').val().indexOf('btnValidateMaterials') != -1) {
confirmExit = false;
}
if (DateOrQtyHasChanged() && confirmExit) {
if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
var message = $('[id$=hfLeaveMessageFF]').val();
if (confirm(message)) {
history.go();
}
else {
window.setTimeout(function () {
window.stop();
}, 1);
}
}
else {
var message = $('[id$=hfLeaveMessage]').val();
return message;
}
}
}

Can I determine what button was clicked to fire an onSubmit event?

I've got an onsubmit handler added to a form like so:
$('#content_form').bind('submit',function(e) {
source = $(e.target).attr('name');
alert(source);
return false;
});
so e.target = the form element. I'm using several submit buttons, and need to determine which one was actually clicked (in modern browsers, that clicked button is the only one that submits, I'm doing this for IE6 compat - it submits the values of all the buttons).
My only thought it to kill any onsubmit events, and then tie click events to the buttons themselves. This would kill the form functionality entirely if javascript wasn't enabled, so I'd like to avoid this.
An easy (but possibly naive) implementation would be to have the onclick handler for each button set a field indicating which one was the last one clicked. In your submit handler, you could then check the value of this field.
$('#content_form input:submit').bind('click', function(e) {
$('#content_form').submit();
// you can now reference this or $(this),
// which should contain a reference to your button
});
Have you checked out the jQuery Form Plugin? It handles submitting forms via ajax very nicely and will handle this problem (along with many others) for you.
Something else you could do is use preventDefault(); instead of return false

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?

Categories

Resources