Fire onblur event before onchange event - javascript

I have a large form that contains several text input fields. Essentially, I need to handle the onchange event for all fields and the onblur events for some fields. When a change is made to a field and the field loses focus, both events fire (which is the correct behavior). The only issue is that I would like to handle the onblur
event before I handle the onchange event.
After some testing in ie and Firefox, it seems that the default behavior is to fire the onchange event before onblur. I have been using the following code as a test...
<html>
<body >
<input type="text" value="here is a text field" onchange="console.log('Change Event!')" onblur="console.log('Blur Event!')" >
</body>
</html>
Which brings me to my questions:
It seems that this behavior is consistent across browsers. Why does onchange fire first?
Since I cannot handle the onblur event for every input element, is there a way I can get onblur to fire before handling the onchange event?

The reason onchange fires first is that once the element loses focus (i.e. 'blurs') the change is usually complete (I say usually because a script can still change the element without user interaction).
For those elements that need onblur handled first, you can disable the onchange handler and fire the onchange (or even a custom event) from the onblur handler. This will ensure the correct order even though it is more work. To detect change, you can use a state variable for that field.
As a general remark though, the need for such synchronicity is a sign that the approach you are using to solve whatever problem you are solving might need more work even though sometimes it cannot be avoided. If you are sure this is the only way, try one of these methods!
EDIT: Just to elaborate on the last point, you would have to follow some assumptions about your event model. Are you assuming that each change event is followed by a blur and goes unprocessed otherwise, or would you like to process each change but those that are followed by a blurget further processing after whatever onblur does with them? In any case if you want to enforce the order the handlers would need access to a common resource (global variable, property, etc.). Are there other event types you might want to use? (input?). Finally, this link has some details for the change event for Mozilla browsers:
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change.
The third 'bullet' addresses the issue of event order.

This is a bit of hack, but it seems to do the trick on most browsers:
<input type="text" value="Text Input" onchange="setTimeout(function(){console.log('Change Event!')}, 0);" onblur="console.log('Blur Event!');" />
You can see a fiddle of it in action here: http://jsfiddle.net/XpPhE/
Here is a little background information on the setTimeout(function, 0) trick: http://javascript.info/tutorial/events-and-timing-depth
Hope that helps :)

Related

Trigger something if both inputs are blurred ONLY

I have a <form> containing two text <input>s side-by-side. When both of these inputs lose focus, I want to do some stuff (send an Ajax request to server and replace them with something else in the DOM). However if I click or tab from one of the inputs to the other, I don't want to do those things.
Setting an onBlur event handler on the <form> element works fine using my setup, but there doesn't seem to be any way to determine if the other form input is my next target. If I examine document.activeElement in my handler, it points to the <body> element (in Chrome) at that point. Only afterwards does it change to the other input.
Is there any way to reliably do what I'm asking? Solutions involving jQuery or other libraries are fine.
So it turns out that event.relatedTarget was what I was looking for - this will return the DOM node receiving focus on a blur event, so it's just a matter of setting a conditional to see if it matches the other field.
However, while this works great in Chrome, relatedTarget currently isn't implemented properly in other browsers. Apparently there's a couple of workarounds:
In IE11, document.activeElement does actually get set to the receiving element at the time the event fires, so you can use that.
In Firefox, apparently event.explicitOriginalTarget can be used instead.
Try ..
Set a global variable that stores what you last blurred from. Call it x.
Set a blur event on all elements, and set x to the last element you blurred from.
Set a focus event on all elements, and if x is not one of your two elements, then run your script.
Give to them both ids, like this:
<input id="id1" />
<input id="id2" />
Then, with jQuery, you can call blur() nested with the two ids.
$('#id1').blur(function(){
$('#id2').blur(function(){
//do your thing
});
});

How to make a real "onchange" event in HTML (no jQuery)?

Please note: I do not want to use jQuery for this (otherwise I like it)
Problem: I have come to situation where I need to do some javascript function after an user changes an input field (e.g. input type="text"). So I said to myself - I remember an onchange event - BUT onchange event runs AFTER user leaves the field, but I need the function to be called for example every time user types a character to that field. Wowhead shows nice example of what I am trying to achieve this (field with placeholder "Search within results...")
Summary: I am looking for a SIMPLE way of detecting REAL onchange event(not the classic HTML one)and through that call a JS function while not using jQuery?
Use onkeyup instead of onchange then.
Following is a simple way of invoking each type of Key Press on field.
input type="text" onkeypress="myFunction()
Get Example here
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeypress
Enjoy..
you can also use onkeyup and onkeydown instead of onkeypress.
Tried onkeypress="myFunction()" or onkeyup="myFunction()"?
There are also events for onfocus and onblur for entering and leaving a textfield :)
You should use "input" event. keyup and keypress don't work if a user modified the value only by a mouse.

onChange is called only when the element loses focus

I want that as you type in the textfield the div changes (I have the code for changing the div already). However the onchange event is only called once you are finished and click outside the textfield. I want it to be called as each letter is typed.
My code:
<input name="platetext" type="text" onchange="setValue(this)">
onChange is fired when the input looses focus I think. onKeyUp should do the trick for you.
There is an 'input' Event you can bind your event Handlers to (I think this was introduced with HTML5).
I made a quick and very dirty example here: http://jsfiddle.net/RdKZH/
This would be the clean approach to this problem (as keyup does not work on copy&paste), but you might want to test if it already works in all browsers you want to support.

javascript text input change event not firing

I have a text type input field and a checkbox.
If I change the text and then click outside the input box (or press enter or tab) the change event is thrown. But if I enter some text and then click directly on the checkbox using the mouse, only the checkbox change event seems to be thrown.
I have the following code:
<input type="text" name="text" class="update">
<input type="checkbox" name="check" class="update">
and this jQuery:
$('.update').change(function(){
console.log($(this));
});
Is this a known problem, and how can I make sure all change events are fired/thrown/caught in this setup?
To fire user changes, use the input event:
$('input').on('input',function(){...})
To fire code changes, use the DOMSubtreeModified event:
$('input').bind('DOMSubtreeModified',function(){...})
If you want to fire both user and code changes:
$('input').bind('input DOMSubtreeModified',function(){...})
The DOMSubtreeModified event is marked as deprecated and sometimes quite CPU time consuming, but it may be also very efficient when used carefully...
I'm not sure if I get it. But for me when I try to type in textfield and then click checkbox by mouse both events are fired. But you have to keep in mind that event 'change' for text input means that this input has to loose focus, as long as field is focused no change event ever will be triggered. This somehow might be your case. Checkboxes/radioboxes work different way tho. No need to loose focus.
Cheers.
P.S.
My test case:
http://dl.dropbox.com/u/196245/index16.html
The change event fires for both because you're listening to the update class.
The change event will not fire unless the input focus switched to other controls

Detecting "value" of input text field after a keydown event in the text field?

My site has an input box, which has a onkeydown event that merely alerts the value of the input box.
Unfortunately the value of the input does not include the changes due to the key being pressed.
For example for this input box:
<input onkeydown="alert(this.value)" type="text" value="cow" />
The default value is "cow". When you press the key s in the input, you get an alert("cow") instead of an alert("cows"). How can I make it alert("cows") without using onkeyup? I don't want to use onkeyup because it feels less responsive.
One partial solution is to detect the key pressed and then append it to the input's value, but this doesn't work in all cases such as if you have the text in the input highlighted and then you press a key.
Anyone have a complete solution to this problem?
NOTE: It's over a decade (!!) since I wrote this answer. The input event has become ubiquitous, and should be used instead of this hack.
What does keydown/keyup even mean for tablet and voice input devices?
The event handler only sees the content before the change is applied, because the mousedown and input events give you a chance to block the event before it gets to the field.
You can work around this limitation by giving the browser a chance to update the field's contents before grabbing its value - the simplest way is to use a small timeout before checking the value.
A minimal example is:
<input id="e"
onkeydown="window.setTimeout( function(){ alert(e.value) }, 1)"
type="text" value="cow" />
This sets a 1ms timeout that should happen after the keypress and keydown handlers have let the control change its value. If your monitor is refreshing at 60fps then you've got 16ms of wiggle room before it lags 2 frames.
A more complete example (which doesn't rely on named access on the Window object would look like:
var e = document.getElementById('e');
var out = document.getElementById('out');
e.addEventListener('input', function(event) {
window.setTimeout(function() {
out.value = event.target.value;
}, 1);
});
<input type="text" id="e" value="cow">
<input type="text" id="out" readonly>
When you run the above snippet, try some of the following:
Put the cursor at the start and type
Paste some content in the middle of the text box
Select a bunch of text and type to replace it
Please, try to use oninput event.
Unlike onkeydown, onkeypress events this event updates control's value property.
<input id="txt1" value="cow" oninput="alert(this.value);" />
Note that in newer browsers you'll be able to use the new HTML5 "input" event (https://developer.mozilla.org/en-US/docs/DOM/window.oninput) for this. Most non-IE browsers have supported this event for a long time (see compatibility table in the link); for IE it's version >/9 only unfortunately.
keyup/down events are handled differently in different browsers. The simple solution is to use a library like mootools, which will make them behave the same, deal with propagation and bubbling, and give you a standard "this" in the callback.
To my knowledge you can't do that with a standard input control unless you roll your own.
Jquery is the optimal way of doing this. Please reference the following below:
let fieldText = $('#id');
let fieldVal = fieldText.val();
fieldText.on('keydown', function() {
fieldVal.val();
});

Categories

Resources