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

Suppose I use the jQuery "placeholder" plugin, which reads the "placeholder" attribute from input elements and simulates it for browsers that do not yet support placeholders.

But I would like $ ("input"). val () worked correctly, that is, return "" if the text in the text field is placeholder text. Anyway, can I override .val () only for these inputs?

+7
javascript jquery
source share
3 answers

try the following:

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 just use $ ("# ele_id"). rVal () to retrieve values. Or if you want to replace the val function (and use it as usual):

 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; }; 
+6
source share

You can override the val() method globally and then check if it is a normal input.

+2
source share

Perhaps you are using a watermark plugin?

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

It is fairly easy to use, just call $("input").watermark("Placeholder text") and it will behave as you described

0
source share

All Articles