Changing the capture value in the .blur () event

I use a function .blur()to execute some code every time a text field loses focus (also when its value does not change).

Now I need to add some logic, which should only be executed when the value of the text field changes. Is there a way to combine the event .change()with .blur()? Or, better, is there a way to find out if the value in my text box has changed using .blur()?

+2
source share
4 answers

Not directly, but you can save the value in the event focus.

sort of

$('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 compare to the current one
        if (original !== this.value){
            // do what you want
        }
    });

, .

$('input')
   .on('change', function(){/*your change code*/})
   .on('blur', function(){/*your blur code*/});
+5

, , . , change() blur(). jsfiddle

$('#in').change(function(){
    alert('change!');
});

, , ,

$('in').on('change blur', function(){
   //code
});
+2

,

var createOnBlurFunc = function(){
    var prevVal = '';
    return function(e){
        if(prevVal === $(this).val()){
           //same value
        } else {
           prevVal = $(this).val();
           // do something
        }
     }
};
$('input').blur(createOnBlurFunc());
0

, , " ":

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 , :input .

0

All Articles