最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Intercept value changes within .blur() event - Stack Overflow

programmeradmin2浏览0评论

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()?

Share Improve this question asked May 23, 2013 at 9:28 daviooohdavioooh 24.7k47 gold badges170 silver badges258 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 11

Not 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.

发布评论

评论列表(0)

  1. 暂无评论