Can you use jQuery $ (this) in single-line code to modify elements?

I am working on a placeholder function in jquery. Right now, I just want the form element to change its value to any of its placeholders. I tried the following code:

$('input:text').val($(this).attr('placeholder')); 

But that will not work. After a little testing, I realized that the problem is using $(this) in this context. How can I change this so that it goes through all the elements of the form and changes their value to its placeholder attribute?

+6
javascript jquery html placeholder
source share
2 answers
 $('input:text').val(function() { return $(this).attr('placeholder'); }); 

or

 $('input:text').attr('value', function() { return $(this).attr('placeholder'); }); 

And here is a live demonstration .

+8
source share

Most of these jQuery setter functions provide a way to specify a function whose return value will be used. This is a way to use $(this) .

 $('input:text').val(function () { return $(this).attr('placeholder'); }); 

jQuery val () Link

+5
source share

All Articles