I’m using Gravity Forms and need to use the label as placeholder text. There are a couple of WordPress plugins but they don’t always work. I also found a solution that added a placeholder field in the Gravity Forms form builder but I don’t really need that.
What I’m trying to do is use jQuery to get the label text and assign that text as the placeholder attribute of the input. I’m using next() here but it only works when the input is not wrapped in a div, I get that. Gravity forms doesn’t play that way.
Here’s my code, you’ll see the first field input is wrapped in a div and so, does not get a placeholder
<!DOCTYPE html>
<html>
<head>
<title>Placeholder</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="form">
<ul>
<li id="field_1" class="gfield">
<label>First Name</label>
<div><input class="first" type="text" /></div>
</li>
<li id="field_2" class="gfield">
<label>Last Name</label>
<input class="last" type="text" />
</li>
<li id="field_3" class="gfield">
<label>Email</label>
<input type="text" />
</li>
</ul>
<input type="submit" value="Submit" />
</div>
</body>
<script>
$("label").each(function() {
var label = $(this);
var placeholder = label.text();
label.next("input").attr("placeholder", placeholder).val("").focus().blur();
});
</script>
</html>
JS Fiddle: http://jsfiddle.net/jsoningram/ezohpxq6/
Thanks in advance.,
If each li element has only one label and input you can use the
.closest()
method together with the.find()
method to do something like this:Demo: http://jsfiddle.net/ezohpxq6/2/
(Or if your label elements had a
for=""
attribute referencing the related input you could use that in your jQuery code, but that would involve changing the html. But it would make clicks on the labels “work”.)