JQuery Click event loads before change event - javascript

I am using a simplified example to describe the issue I am facing.
I have the following HTML markup:
<input ng-model="something" style="margin-top:8px;"/>
And, I have two HTML buttons:
<button id='submit'>Save</button>
<button id='btnGetAnalyzerInput'>Generate Analyzer File </button>
I used jQuery's change event on my input (to track whether any changes have been made to the input - by maintaining a simple JS variable).
When the user clicks "Generate Analyzer file button", what I want to is this:
Look up the JS variable to find out whether any changes have been made.
If yes, then prompt the user to save changes (window.dialog)
However, I find that when the focus is still on the input element, and when the button is clicked, the click event runs before the OnChange event. In all other cases, it is the OnChange event which gets fired before the click event (and so my code works as expected).
Is there any way to ensure that for such a scenario, the click event runs after the onChange event?
I am using Google Chrome to test my application.
Note :
Both events work as expected - the OnChange event gets fired when the textbox loses focus.
I can't use the keypress event since I want to track changes.

You could have the click event call the same function as the OnChange event. Something like this:
function OnChange(){
//Do stuff for on change;
}
function ClickEvent(){
OnChange();
//continue with generate stuff
}
You you may need to set up and pass in arguments to the OnChange function, depending on how you are accessing the data you need. If you need more guidance, post more of your code.

Related

stopping onclick event handler

I have some working code that I'm now using in slightly different context. The working part is that I use objects onclick event to bring up a form to send an e-mail. When this in an HTML page, it works fine. I would have a lot of buttons that look like this:
<button id="mail-c1" onclick="initMailFormButton(this.id, 'someone','somedomain.com','a subject')">Someone's Name</button>
The entire form is created in javascript and has its own submit and cancel buttons but is within the button element. In order to be able to enter data into the form, I need to kill the onclick event then restore it after I've submitted or cancelled the e-mail. The onclick handler starts out with:
function initMailFormButton(mailId, eName, eDomain, eSubject) {
myFormLocation = document.getElementById(mailId);
stopFormClick(myFormLocation);
where the stopFormClick function is:
function stopFormClick(myFormLocation) {
saveOnclick = myFormLocation.onclick;
myFormLocation.onclick = null;
}
This has the bug that it doesn't handle someone opening multiple forms at once, but that's not my immediate concern. I'll fix it outside of this discussion.
The submit and cancel buttons in the generated form both restore the onclick event handler so you can open and close the form multiple times quite happily.
My new case is that I'm generating HTML page from a database. I'm using HTML datasets to store the previously hard-coded information like so:
emailButton.setAttribute("data-mailname", emailName);
emailButton.setAttribute("data-maildomain", emailDomain);
emailButton.addEventListener("click", function() { initMailFormButton(this.id, this.dataset.mailname, this.dataset.maildomain, ""); }, false);
The information being retrieved is correct and the form appears in the correct location. However, I can't enter information because the original onclick handler kicks in when I click in the first form field and generates another form...
The only clue I have is that when I look at the value of the onclick event being saved in the static HTML pages, it has the expected value but it is null in the generated pages. I find this confusing because I am passing the (unique) element id to the routine so it should be getting to the correct element.
Can anyone help me on this one. Meanwhile, I'll fix the event handler bug I mentioned above.
OK. So it's that there is a difference between click and onclick. The onclick event handler wasn't set so it is null. I changed setting the click event listener to setting the onclick attribute as:
emailButton.onclick =
function() { initMailFormButton(this.id, this.dataset.mailname, this.dataset.maildomain, ""); };
and everything works nicely.
To handle the limitation I'd noted earlier, I made the saveOnclick variable into an associative array keyed by the button id. Now people can have as many buttons clicked as they want - although wanting to have more than one is probably rare.

simulate onChange event to fire on HTML input box

I have jQuery that uses the change event from a selection box to update a input box on the form. I need the input box to fire it's change event when I update it's value.
This link on MSDN shows a way to simulate the click event. Is there a technique I can use to simulate a change event?
You can use trigger():
$('#input-id').trigger('change');
You can trigger change event handler. You can simply call it like that:
jQuery('#my_field').change();
which is a shortcut to:
jQuery('#my_field').trigger('change');
See more on the documentation of .change() (its third, attribute-less variation).
This should theoretically do it:
<input id="textinput" value="somevalue" name="somename" />
<script type="text/javascript">
function doSomethingOnInputChange(e) {
console.log('input on change');
}
$('#textinput').bind('change', doSomethingOnInputChange);
$('#textinput').trigger('change');
</script>
It binds an event handler to a custom 'change' event and then fires the event.
There are several good jQuery based answers already (though you didn't use a jQuery tag) but there's another approach that can work for you if you're binding the change event to call a function.
Say you've already bound the change event to the doSomethingOnInputChange function as in Vlad's answer...
Rather than simulating an event by triggering 'change' you can directly call doSomethingOnInputChange - that is, instead of doing:
$('#textinput').trigger('change')
your javascript just makes a call to the same function that gets called anyway when you trigger the event:
doSomethingOnInputChange( ... );
You may or may not want to pass the #textinput DOM element as a parameter in a direct call, or an event parameter (but providing your own event parameter makes this approach hardly worthwhile) -- those depend on what you need to do in the function.

Is this a core misunderstanding of the default click event on checkbox inputs, or flawed code?

When binding to a click event for a checkbox input, the checkbox is already toggled by the time my event handler runs and, more oddly, the toggle is reversed after my event handler runs if I specify event.preventDefault();
<input id="foo" type="checkbox"/>
function clicked(evt) {
alert(document.getElementById('foo').checked);
evt.preventDefault();
}
document.getElementById('foo').addEventListener('click',clicked);
[tested in chrome and firefox]
JSFiddle for that code
The alert will respond "true" (or the opposite state of the checkbox pre-click). After you dismiss the alert, the checkbox toggles back.
So, I guess the questions are,
What is the actual default event being prevented? Am I wrong in assuming my event handler should be running before the state is changed? Is there a way to legitimately intercept a checkbox click?
And why in the world is the preventDefault causing the re-toggling the checkbox?
The actual default event being prevented is the click event. The misunderstanding probably occurs because you are thinking of the event as firing after the actual click has been fully processed (i.e. the checkbox has been toggled) while in reality the event model stipulates that the handler fires while the event is being processed.
If it helps, another model I 've found useful in explaining how it all works is the database transaction model: think of your event handler as being invoked as part of a transaction, inside which the checkbox has already been toggled.
If you read the state of the checkbox, you will find it toggled (the "write" has been sent to the database).
However, you can still decide to rollback the transaction (in which case the write is undone and the checkbox is toggled back to its original value).

DOM problem with click initiating a focusout event on a different input

I have an <input type=text> with focusout event handler
I have a <button> with click event handler
Focusout checks whether format in input box is correct. It does so by testing input value against a regular expression. If it fails it displays a message (a div fades-in and -out after some time) and refocuses my input by calling
window.setTimout(function() { $(this).focus(); }, 10);
since I can't refocus in focusout event handler. focusout event can't be cancelled either. Just FYI.
Click collects data from input elements and sends it using Ajax.
The problem
When user TABs their way through the form everything is fine. When a certain input box failes formatting check it gets refocused immediately after user presses TAB.
But when user doesn't use TAB but instead clicks on each individual input field everything works fine until they click the button. focusout fires and sets time-out for refocusing. Since time-out is so short focusing happens afterwards and then click event fires and issues an Ajax request.
Question
I have implemented my formatting check as an independent jQuery plugin that I want to keep that way. It uses .live() to attach focusout on all input fields with a particular attribute where format regular expression is defined.
Data submission is also generic and I don't want to make it dependant on formatting plugin. They should both stay independent.
How can I prevent click event from executing without making these two plugins dependant?
Example code I'm fiddling with
After some searching I've seen that all major browser support document.activeElement but I can't make it work in Chrome. FF and IE both report this being the active element, but Chrome always says it's BODY that is active even though click fired on the button element.
Check this code http://jsfiddle.net/Anp4b/1/ and click on the button. Test with Chrome and some other browser and see the difference.
You could use a flag...
Live demo: http://jsfiddle.net/Anp4b/4/
So your question is:
How can I prevent click event from executing without making these two plugins dependent?
Well, you obviously cannot prevent the click event. If the user wants to click the button, he will, and the click event will trigger. There's nothing you can do about that.
So the answer to the above question is: You cannot.
Based on the current conditions, you have to - inside the click handler - retrieve the validation result, and based on that result, decide if form submission should or should not occur.
JS Code:
$("#Name").focusout(function(){
var that = this;
valid = this.value.length ? true : false;
!valid && window.setTimeout(function() {
$(that).focus();
}, 0);
});
$("#Confirm").click(function(e) {
if ( !valid ) { return false; }
e.preventDefault();
alert('AJAX-TIME :)');
});
HTML Code:
<input type="text" id="Name">
<button id="Confirm">OK</button>
Is there are reason you use .focusout instead of .blur?
Using a flag is a good idea, but I would rather use a class on the element. By using classes to determine the state you can also style it accordingly. Here's my example based on your fiddle.
Another solution that hopefully gives the result you are looking for.
1) Create a named click handler:
var clickHandler = function(e){ /** submit form or whatever you want to do**/ };
$("button").click(clickHandler);
2) Add the following to the focusout event when it's failing validation:
$("button").unbind("click", clickHandler).one("click", function(){ button.click(clickHandler); return false;});
You can find an example of this here.

Function run multiple times on textfield focus

I want to call a function when I have a textfield focused and then unfocus it (whether I press TAB or click elsewhere with the mouse) and I used this code:
$("#settings_view #my_profile_div input").focus(function() {
$(this).blur(function() {
change_my_profile();
});
});
When I first run it (have a field focused then unfocus it) it runs one time as expected. However, the second time it calls the function change_my_profile twice. The third time it ran 3 times and so on.
What is the problem here and how do I solve it? (I tried with 'throw' after change_my_profile and then it only ran one time, but I want to locate the problem anyway).
it is binding a blur event every time a focus event is initiated, that's why you are getting multiple executions
try
$(this).bind("blur",function(){
change_my_profile(this);
})
and then in your change_my_profile function do the following
function change_my_profile(el){
$(el).unbind("blur");
//rest of the change_my_profile code goes here
}
The .focus() and .blur() functions assign handlers to the 'focus' and 'blur' events repsectively. So every time the user focuses the textbox, your code is adding a new event handler to the 'blur' event. What you want is:
$("#settings_view #my_profile_div input").blur(change_my_profile);
You need to remove the event handler after successful execution. Otherwise, you are stacking handler upon handler and they all get triggered. I think in JQuery that is done using unbind()
Your code is asking jQuery to add (append) an onBlur event handler to an input field every time the user enters the field. So, your same event handler function gets appended over and over again. Are you simply trying to trigger a function to run when the user moves out of a field? If that is the case, you can simply use .blur to attach the onBlur handler once.

Categories