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 thedefaultTextbefore clearing it, and in yourblur()function, you just need to check if theval()is empty before setting thedefaultText. If you are going to be working with multiple inputs, it’s better to use a class rather than ID, so your selector would beinput.inputwhen the class is “input”. Even if it was an ID, you would reference it asinput#input.Set it in action in this jsFiddle.