Reputation: 117
How can I add color style just to the value of this input element (red, for example) while preserving the color of the input text black? I'd like to inject it into the external script and not embed it inline with the input element, if possible! Thanks!
HTML
<input type="text" value="Search apples" class="noquery" />
JQuery
$('input.noquery').on('focus',function(){
if (!$(this).data('defaultText'))
$(this).data('defaultText',$(this).val());
if ($(this).val()==$(this).data('defaultText'))
$(this).val('');
});
$('input.noquery').on('blur',function(){
if ($(this).val()=='')
$(this).val($(this).data('defaultText'));
});
Upvotes: 0
Views: 1106
Reputation: 20189
You mean like this ?
You should also cache your element it will improve performance
$(document).ready(function(){
$('input.noquery').on('focus',function(){
if
(!$(this).data('defaultText'))
$(this).data('defaultText',$(this).val());
if
($(this).val()==$(this).data('defaultText'))
$(this).css('color', 'black').val('');
});
$('input.noquery').on('blur',function(){
if
($(this).val()=='')
$(this).css('color', 'red').val($(this).data('defaultText'));
});
});
CSS
input{
color:red;
}
All I done was set the default css color to red. then when you change the value to ''
change the color to black then when you change it back to the default value change it back to red
If you need it the other way around
Demo
Upvotes: 0
Reputation: 32921
You should probably use the color property and use the placeholder attribute for the default value.
<style> input { color: red; } </style>
<input placeholder="Bill" name="name">
Here's a demo, including styling placeholder text: http://jsbin.com/uqusut/1/edit
You may also just want to simply style it when it has focus.
input { color: blue; }
input:focus { color: red; }
Upvotes: 1
Reputation: 46
Is this what want?
$(document).ready(function(){
$('input.noquery').on('focus',function(){
if
(!$(this).data('defaultText'))
$(this).data('defaultText',$(this).val());
$(this).addClass('red');
if
($(this).val()==$(this).data('defaultText'))
$(this).val('');
});
$('input.noquery').on('blur',function(){
if (($(this).val()=='')) {
$(this).val($(this).data('defaultText'));
$(this).removeClass('red');
$(this).addClass('black');
}
});
});
CSS:
.red { color: red; }
.default { color: black; }
Upvotes: 0
Reputation: 59336
Is this what you want?
$(document).ready(function(){
$('input.noquery').on('focus',function(){
if (!$(this).data('defaultText')) {
$(this).data('defaultText',$(this).val());
$(this).addClass("watermark");
}
if ($(this).val()==$(this).data('defaultText')) {
$(this).removeClass("watermark");
$(this).val('');
}
});
$('input.noquery').on('blur',function(){
if ($(this).val()=='')
{
$(this).val($(this).data('defaultText'));
$(this).addClass("watermark");
}
});
});
Fiddle: http://jsfiddle.net/6KbqK/1/
Upvotes: 1