简体   繁体   中英

Input focus Jquery issue

I am trying to fix this piece of code which on Click, removed the input's value, and on Blur returns the value back into the input. You can see my jsFiddle here to see what I mean:

JSfiddle

The problem

It seems to work for the first two inputs, but then the rest don't seem to do anything. It also appears to not work with the textarea. Strange behavior here but I'm sure a Javascript head can sort this one out.

Thanks alot!

And now it works: :-) http://jsfiddle.net/maniator/3Ys7c/3/

Use the jQuery data() attrbute:

jQuery(document).ready(function($) {
    $("input, textarea").focus(function() {
        if (!$(this).data('original')) {
            $(this).data('original', $(this).val());
        }
        if ($(this).val() == $(this).data('original')) {
            $(this).val('').css({
                'color': "#999999",
                'background-color': '#c6e9ff'
            });
        }
    });
    $("input, textarea").blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).data('original')).css({
                'background-color': '#ffffff'
            });
        }
    });
});

The reason why yours did not work is because you were using this.id which none of them had. If you just use the data attribute of each input, then each input knows what it should and should not be :-)

或者只是给您的元素一个id=""属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM