-1

I have some code here in JS and I can't figure out why it isn't doing what I want it to do. Basically, I have a search bar that should write "Search..." it in. When the user clicks on it, the text goes away and the bar goes blank. If the user clicks away without filling any text in, the "Search..." text returns.

Otherwise, the text the user enters stays in the bar. Up until this point my code works fine. The issue is this; when the user inputs something AND THEN takes it away, the bar remains blank, whereas the "Search..." text should return. (Notice: This does not occur if the user simply clicks on the bar and then clicks away; the default text returns as it should. It only happens if the users enters something and then takes it away.)

I can not figure out why this is happening. Any help would be greatly appreciated. Here is my JS code:

$(document).ready(function () {
    var search_default = 'Search...';
    $('input[type="search"]').attr('value', search_default).focus(function () {
        if ($(this).val() == search_default) {
            $(this).attr('value', '');
        }
    }).blur(function () {
        if ($(this).val() == '') {
            $(this).attr('value', search_default);
        }
    });
});
hjpotter92
  • 78,589
  • 36
  • 144
  • 183

2 Answers2

0

Use .val(value) instead of attr('value',value)

$(document).ready(function () {
    var search_default = 'Search...';
    $('input[type="search"]').val(search_default).focus(function () {
        if ($(this).val() == search_default) {
            $(this).val('');
        }
    }).blur(function () {
        if ($(this).val() == '') {
            $(this).val(search_default);
        }
    });
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • Thanks that works! I'm new at JS (just started today). Can you explain why .val(value) works as opposed to attr('value', value)? – user3426380 Jul 29 '14 at 10:14
  • glad to help you :). See [this](http://stackoverflow.com/questions/8312820/jquery-val-vs-attrvalue) for explanation – Bhushan Kawadkar Jul 29 '14 at 10:18
0

If you can edit the HTML, this is how i would do it:

JSFIDDLE DEMO - EDITED HTML

If you cannot edit the HTML, you would need to create the data-default attribute

JSFIDDLE DEMO 2 - NON EDITED HTML

Add a data-default tag to the element

<input type="search" data-default="Search..." value="Search...">

And the jQuery

$(document).ready(function(e){
    // when you focus on the search input
    $('input[type=search]').on('focus',function(e){

        // if the value is the same as the default value
        if( $(this).val() == $(this).attr('data-default') )
        {
            // make the value blank
            $(this).val('');
        }

    // when you move out of the search input
    }).on('blur',function(e){

        // if there is no value (blank)
        if( !$(this).val() )
        {
            // add back the default value
            $(this).val( $(this).attr('data-default') );
        }
    });
});