-1

How do I remove the value when element is selected?

<input type="text" value="Name" />

If the input box is selected, as in a single mouse click I want to clear the value. If there is not typed value when this input box, I want to restore stock value, in this case "Name". However, if there is something other than "empty space" in the box, it retains that string value.

$('input').on('select', function() {
    if(this).val() == 'Name') {
        $(this).val('');
    };
});

$('input'.on('unselect', function() {
    if($(this).val() == '') {
        $(this).val('Name');
    };
});

I am very aware the 'select' and 'unselect' are incorrect.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
marcwebdude
  • 73
  • 2
  • 14

1 Answers1

4

Use focus and blur events:

$('input').on('focus', function() {
    if($(this).val() == 'Name') {
        $(this).val('');
    };
});

$('input'.on('blur', function() {
    if($(this).val() == '') {
        $(this).val('Name');
    };
});

Alternatively, use HTML placeholder attribute:

<input type="text" placeholder="Name" />
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177