开发者

Can I override jQuery .val() for only some input elements?

开发者 https://www.devze.com 2023-01-12 06:06 出处:网络
Suppose I\'m using a \"placeho开发者_开发百科lder\" jQuery plugin that reads the \"placeholder\" attribute from input elements and simulates it for browsers that don\'t yet support placeholders.

Suppose I'm using a "placeho开发者_开发百科lder" jQuery plugin that reads the "placeholder" attribute from input elements and simulates it for browsers that don't yet support placeholders.

But I would still like $("input").val() to work properly -- that is, to return "" if the text in the textbox is the placeholder text. Is there anyway I can override .val() just for these inputs?


try this:

jQuery.fn.rVal=function() {
    if(this[0]) {
        var ele=$(this[0]);
        if(ele.attr('placeholder')!=''&&ele.val()==ele.attr('placeholder')) {
            return '';
        } else {
            return ele.val();
        }
    }
    return undefined;
};

and simply use $("#ele_id").rVal() to retrieve values. Or if you want to replace the val function (and use it as normal):

jQuery.fn.rVal=jQuery.fn.val;
jQuery.fn.val=function(value) {
    if(value!=undefined) {
        return this.rVal(value);
    }
    if(this[0]) {
        var ele=$(this[0]);
        if(ele.attr('placeholder')!=''&&ele.rVal()==ele.attr('placeholder')) {
            return '';
        } else {
            return ele.rVal();
        }
    }
    return undefined;
};


You can override the val() method globally, then check whether it's a normal input.


Could you possibly use a watermark plugin?

http://code.google.com/p/jquery-watermark/

It's pretty easy to use, just call $("input").watermark("Placeholder text") and it will behave in the way you described

0

精彩评论

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

关注公众号