Reputation: 895
I have multiple text box like this. I want to apply the text on blur and empty when it get focused. I can able to achieve this for single text box. How i can pass the current element id instead of the hard coding the "#name" value in JavaScript function ?
$(document).ready(function(){
$('#Name').focus(function()
{
var $ele = $(this).attr('id');
$(this).val('');
$(this).css('color', '#000000');
});
$('#Name').blur(function()
{
var $ele = $(this).attr('id');
$(this).val($ele);
$(this).css('color', '#a9a9a9')
});
});
<input id="Name" type="text" value="" name="Name">
<input id="Phone" type="text" value="" name="Phone" >
<input id="Email" type="text" value="" name="Email">
Upvotes: 0
Views: 1298
Reputation: 23208
You can select all input by $('input')
and you can put filter text inputs using [type="text"]
; You can take benefits of jQuery chaining.
$(document).ready(function(){
$('input[type="text"]').focus(function()
{
var $ele = $(this).attr('id');
$(this).val('');
$(this).css('color', '#000000');
}).blur(function()
{
var $ele = $(this).attr('id');
$(this).val($ele);
$(this).css('color', '#a9a9a9')
});
});
You can directly set value of input fields in html
<input id="Name" type="text" value="Name" name="Name">
OR Apply default values on page load as:
$('input[type="text"]').each(function(){
var $ele = $(this).attr('id');
$(this).val($ele);
$(this).css('color', '#a9a9a9')
});
HTML
<input id="Name" type="text" value="" name="Name">
<input id="Phone" type="text" value="" name="Phone" >
<input id="Email" type="text" value="" name="Email">
Upvotes: 2
Reputation: 2251
You need to modify you js
$(function(){
$('input').focus(function()
{
$(this)
.val($(this).attr('name'))
.css('color', '#000000')
}).blur(function()
{
$(this).css('color', '#a9a9a9')
});
})();
if you set value on 'blur' you will lost current value... I am not sure that it is exactly what you want
Upvotes: 1
Reputation: 1544
Look into jQuery Selectors. What you're doing now is using the ID as the selector. You have tons of different options...
You can replace "#Name" with "input" if you want it to apply to all inputs on the page, or you could even add a common class 'class="test"' to all the elements you want to trigger the script and then replace the "#Name" with ".test" or "input.test" for only input elements with that class name.
Upvotes: 0
Reputation: 22817
You may select all inputs with $('input[type="text"]')
, but I think you just want to use the placeholder
HTML attribute.
Upvotes: 0
Reputation: 6232
apply it to input
instead of #name
.
this will work for all inputs.
or give a .class
to the elements you want to change.
Upvotes: 0