Reputation: 18029
I am having a form with label overlaying the input. Like in the below image
Below is a code example of the same.
<label for="edit-submitted-name--2">
Name
<span class="form-required" title="This field is required.">*</span>
</label>
<input id="edit-submitted-name--2" class="form-text required" type="text" maxlength="128" size="35" value="" name="submitted[name]">
I want to use jquery and hide the label each time a user focus on the input. Label should only be visible if the input is empty or if the input is not in focus.
$("input").focus(function () {
//hide the label corresponding to this input
});
How do i select the label corresponding to this input using jquery?
Note: I cant change anything much in the html as its generated by a module in Drupal.
Upvotes: 2
Views: 4078
Reputation: 17285
placeholder attribute is the right tool for this job:
<input id="edit-submitted-name--2" class="form-text required" type="text" maxlength="128" size="35" placeholder="Name *" name="submitted[name]">
http://www.w3schools.com/html5/att_input_placeholder.asp
But don't forget that label-less input fields are bad practice. Placeholders should be treated like a hint. They are not a replacement for labels.
Upvotes: 5
Reputation: 95023
Select the previous element from the current element.
$(this).prev("label").hide();
and
$(this).prev("label").show();
However, this isn't the purpose of the label element.
Upvotes: 3
Reputation: 25197
Remy Bach has created Super Labels which does what you want, I would use his code, but if you're looking for something slightly different then you can use his code as a template.
https://github.com/remybach/jQuery.superLabels
Upvotes: 1