I have the following code so that when a users selects an input box the value will disappear, but the default value will then be re-inserted once a user clicks off it.
$(function() {
var defaultText = '';
$('input[id=input]').focus(function() {
defaultText = $(this).val();
$(this).val('');
});
$('input[id=input]').blur(function() {
$(this).val(defaultText);
});
});
However, that's not exactly how I want it. If a user inserts text I don't want the default text to then override what the user has put. I'm also fairly new to jQuery so any help would be greatly appreciated.
In your focus()
method you should check to see if it equals the defaultText
before clearing it, and in your blur()
function, you just need to check if the val()
is empty before setting the defaultText
. If you are going to be working with multiple inputs, it's better to use a class rather than ID, so your selector would be input.input
when the class is "input". Even if it was an ID, you would reference it as input#input
.
// run when DOM is ready()
$(document).ready(function() {
$('input.input').on('focus', function() {
// On first focus, check to see if we have the default text saved
// If not, save current value to data()
if (!$(this).data('defaultText')) $(this).data('defaultText', $(this).val());
// check to see if the input currently equals the default before clearing it
if ($(this).val()==$(this).data('defaultText')) $(this).val('');
});
$('input.input').on('blur', function() {
// on blur, if there is no value, set the defaultText
if ($(this).val()=='') $(this).val($(this).data('defaultText'));
});
});
Set it in action in this jsFiddle.
In your blur handler just check if the user has not write anything, in that case put back the default text, like this:
$('input[id=input]').blur(function() {
if ($(this).val() == '') {
$(this).val(defaultText);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With