A function which prepopulates textfields with value of label
I have a form which looks like so:
- <form class="subscribe" id="form-5" method="post" accept-charset="UTF-8" action="/subscribe/">
<div>
<div id="edit-name-1-wrapper" class="form-item">
<label for="edit-name-1">Name: <span title="This field is required." class="form-required">*</span></label>
<input type="text" class="form-text required" value="" size="20" id="edit-name-1" name="name" maxlength="128">
</div>
<div id="edit-mail-wrapper" class="form-item">
<label for="edit-mail">Email Address: <span title="This field is required." class="form-required">*</span></label>
<input type="text" class="form-text required" value="" size="20" id="edit-mail" name="mail" maxlength="128">
</div>
<input type="submit" class="form-submit" value="Subscribe" id="edit-submit-1" name="op">
</div>
</form>
I want to prepopulate the value of the two textfields with the field label e.g. Name, Email Address, until the fields are in focus.
I have this working for the Name field:
- $('#form-5 label').hide();
// Prefill newsletter name field with label
$("form#form-5 input[name='name']").val('Name').focus(function() {
// Clear on focus
if ($(this).val() == 'Name') {
$(this).val('');
}
})
.blur(function() {
// Put field title back in on blur
if ($(this).val() == '') {
$(this).val('Name');
}
});
Obviously I can repeat this code on the email field as well, but wondered if there is a way to make it a function with the label value not hardcoded so I can use the same technique on forms with many fields.