Search code examples
phpjavascriptsearchuitextfieldsearch-form

Change search form behaviour


  1. How do I separately style the text inside the search field (on the right)? I want to have light grey color when there's a default text (SEARCH) and I want a black color when a person inputs a word.

    • I tried wrapping the function inside the new div tag but no use, it gives me a PHP error.

    • I used FireBug to track the problem but couldn't figure it out on my own.

  2. When you write something in the search (don't press Enter) and then click away, the text you wrote stays inside a search field. What can I do to get the effect so that whenever you click away from the search field, it resets to a default word (SEARCH in this case)?

    • I tried playing with onblur and onfocus but I don't know what to change to get a desired behavior.

    • I also used a code for form reset but that just gives me the button that you have to click to reset to default text.

  3. If the answer to the second question is too complex, I'd like to get the following instead:

    • When the site loads - search field says SEARCH.

    • When you input something (don't press Enter) and click away, the text that you input stays BUT...

    • ... When you click that search field again, the previously input text is completely selected so that if you start writing something new, the search field shows only the new text. (At the moment, if you click the filed after clicking away, your new text is just added to the text you input before it).


Solution

  • This works for both #1 and #2 for me (tested in FF, not sure about IE).

    The onclick checks if the default value is still in the search field, if it is, it gets cleared out and the user can type something in black text.

    When they click away, the onblur event fires and checks if the default value is present. If it isn't, the value gets reset and changed to a light gray.

    <input type="text" name="search" value="SEARCH" style="color: #DDDDDD;"
        onclick="javascript: if( this.value == 'SEARCH') { this.value = ''; this.style.color = '#000000'; } "
        onblur="javascript: if( this.value != 'SEARCH') { this.value = 'SEARCH'; this.style.color = '#DDDDDD'; }" />