Reputation: 756
First of all please visit this fiddle: http://jsfiddle.net/asif097/z6zsc
What I wish for, is this jquery code will run individually for every text input with the class. At this moment this code is running over both text input field at once.
Here is My Jquery code:
$(".first-name-input").after("<div class='first-name-input-value'>First Name</div>");
$(".first-name-input").focus(function(){
$(".first-name-input-value").hide();
});
$(".first-name-input").blur(function(){
if($(this).val() == ""){
$(".first-name-input-value").show();
}
});
$(".first-name-input-value").click(function(){
$(".first-name-input").focus();
});
I also tried this one: http://jsfiddle.net/z6zsc/1
But didn't succeed. How to fix it?
Thanks.
Upvotes: 1
Views: 771
Reputation: 3243
Another approach is to use inline javascript for your input elements,. Which you could also break into a separate function call...
Your updated html would be something like this:
<input id="first_name" name="first_name" type="text" size="25" placeholder="First Name"
onfocus="if (this.value == 'First') { this.value = ''; this.style.color = '#000000'; } "
onblur="if (this.value == '') { this.value = 'First'; this.style.color = '#909090'; } "
value="First"/>
This will achieve the effect you are going for, and can be used individually per input...
Here is an updated fiddle- http://jsfiddle.net/z6zsc/8/
Upvotes: 0
Reputation: 123739
I think probably may want to look at the HTML5 placeholder
attribute.
<input type="text" class="first-name-input" placeholder="First Name" required="required"/>
or fix your code:- http://jsfiddle.net/vYtmC/
$(".first-name-input").after("<div class='first-name-input-value'>First Name</div>");
$(".first-name-input").focus(function(){
$(this).next().hide();
});
$(".first-name-input").blur(function(){
if($(this).val() == ""){
$(this).next().show();
}
});
$(".first-name-input-value").click(function(){
$(this).prev().focus();
});
Upvotes: 2
Reputation: 707148
In your event handlers, you need to refer to $(this)
so the handler operates only on the object that triggered the event rather than operating on all the objects.
Since you're trying to operate on another neighboring element, you will need to find that other element relate to the this
element.
Since the .first-name-input-value
object is right after the first-name-input
object, you could use this:
$(".first-name-input").focus(function(){
$(this).next().hide();
});
FYI, since you're essentially trying to implement HTML5 placeholder functionality, you could also just get a pre-written shim for HTML5 placeholders and use that. This problem has been solved many times already. You don't have to reinvent it. I'm sure the right Google search will find you several prewritten options.
Upvotes: 1