I'm working on a placeholder function in jquery. Right now, I just want the form element to change its value to whatever its placeholder is. I tried the following code:
$('input:text').val($(this).attr('placeholder'));
But it doesn't work. After testing it a little, I realized the problem is with using $(this)
in that context. How can I change this so that it will loop through all form elements and change their value to their placeholder attribute?
$('input:text').val(function() {
return $(this).attr('placeholder');
});
or:
$('input:text').attr('value', function() {
return $(this).attr('placeholder');
});
And here's a live demo.
Most of these setter jQuery functions provide a way to specify a function whose return value will be used. This is a way to make use of $(this)
.
$('input:text').val(function () {
return $(this).attr('placeholder');
});
jQuery val() Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With