I'm using .blur()
function to execute some code every time a text field loses focus (also when its value doesn't change).
Now I need to add some logic that must be executed only when text field value changes. Is there a way to bine .change()
event with .blur()
? Or, better, is there a way to know if the value in my text field is changed just using .blur()
?
I'm using .blur()
function to execute some code every time a text field loses focus (also when its value doesn't change).
Now I need to add some logic that must be executed only when text field value changes. Is there a way to bine .change()
event with .blur()
? Or, better, is there a way to know if the value in my text field is changed just using .blur()
?
4 Answers
Reset to default 11Not directly, but you can store the value on focus
event..
something like
$('input')
.on('focus',function(){
// store the value on focus
$(this).data('originalValue', this.value);
})
.on('blur',function(){
// retrieve the original value
var original = $(this).data('originalValue');
// and pare to the current one
if (original !== this.value){
// do what you want
}
});
Of course you could just bind different handlers for each event..
$('input')
.on('change', function(){/*your change code*/})
.on('blur', function(){/*your blur code*/});
The event change is trigger every time that the field lose the focus and the content has change. I think what you need is to use change()
instead of blur()
. Take a look at this jsfiddle
$('#in').change(function(){
alert('change!');
});
If what you need is to execute the same code when the input loses the focus and when the value changes, you can bine both events
$('in').on('change blur', function(){
//code
});
you can use closure to store the previous value and pare them later
var createOnBlurFunc = function(){
var prevVal = '';
return function(e){
if(prevVal === $(this).val()){
//same value
} else {
prevVal = $(this).val();
// do something
}
}
};
$('input').blur(createOnBlurFunc());
I think this is a more generalized way, for those that are created on the fly:
var $bodyEl = $('body'), inputOldValue;
$bodyEl.on('focus', 'input, textarea, select', function () {
inputOldValue = $(this).val();
});
$bodyEl.on('blur', 'input, textarea, select', function () {
if (inputOldValue != $(this).val()) {
$(this).trigger('changeBlur');
}
});
input, textarea, select
is faster than :input
as a selector.