开发者

jquery .change overridden by .blur

开发者 https://www.devze.com 2023-04-02 08:39 出处:网络
I have a form where the input elements initially are a light blue, and I wanted the following: a) when you focus on them they become white

I have a form where the input elements initially are a light blue, and I wanted the following: a) when you focus on them they become white b) when you blur off them they return to the original blue ONLY IF the content was changed.

I had the following code:开发者_运维百科

$(":text, select, textarea").change(function() {    
                        $(this).css("background-color", "white");
                    });
                    $(":text, select, textarea").blur(function() {  
                        $(this).css("background-color", "white");
                    });

This didn't work because the .blur overrode the .change and changed back to blue regardless if the input was changed. How can I avoid this and accomplish what I am trying to do? The only way I had figured it out was to take out the blur and use a css :focus to make it change to white when focused on (and the .change dealt with it when it leaves focus), but the problem is that :focus doesn't work for IE7 and I would like to make it do so. Any ideas?


change is for when the value changes, not the focus. Do you want:

$(":text, select, textarea").focus(function() {    
    $(this).css("background-color", "white");
});

$(":text, select, textarea").blur(function() {    
    $(this).css("background-color", "blue");
});

instead?


First of all, you should've used focus instead of change. Second, to change the original background to blue only if the value is changed, you'll need to store the old value inside a variable. And then, when the element is blurred check the value again and see if it matches the old one. If not, change the background color.

Have a look at the javascript code.

http://jsfiddle.net/rsqqL/1/


Neither of the two answers above did what I want. For both of them, if I clicked out of the input box it turned blue regardless if I had any input in them or not. But, I modified the last answer and got the result I needed:

$(":text, select, textarea").focus(function() {    
$(this).css("background-color", "white");
$(this).blur(function(){
    var newVal = $(this).val();
    if (newVal == '')
    {
        $(this).css("background-color", "blue");
    }
    else
        { $(this).css("background-color", "white");
    }    
});
});
0

精彩评论

暂无评论...
验证码 换一张
取 消