Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use jQuery's $(this) in a one-line code to modify elements?

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?

like image 491
Zak Avatar asked Mar 12 '11 15:03

Zak


2 Answers

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

or:

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

And here's a live demo.

like image 117
Darin Dimitrov Avatar answered Sep 21 '22 11:09

Darin Dimitrov


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

like image 22
kapa Avatar answered Sep 21 '22 11:09

kapa