james6848
james6848

Reputation: 1667

Clearing a default value in a search box with jQuery

Can't seem to achieve this simple functionality! All I want is to clear a default search term in an input box when it is clicked. The following works up to a point but clears any other text entered, I would've thought resetting search_form_text should have solved this:

search_form_text = $('#block-search-0 #edit-search-block-form-l').attr('value');

if (search_form_text == 'Enter search keywords here') {

        $('#block-search-0 #edit-search-block-form-l').click(function() {           
            $('#block-search-0 #edit-search-block-form-l').attr('value', '');
            search_form_text = '';
        });

    }

Hmmmm... :)

Upvotes: 1

Views: 6300

Answers (4)

AdrianoFerrari
AdrianoFerrari

Reputation: 2158

Found this solution here, seems cleaner to me: http://snipplr.com/view/15360/jquery-clear-default-input-values/

(function($){
$.fn.clearDefault = function(){
    return this.each(function(){
        var default_value = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == default_value) $(this).val("");
        });
        $(this).blur(function(){
            if ($(this).val() == "") $(this).val(default_value);
        });
    });
};
})(jQuery);

// Usage: $('input.clear-default').clearDefault();

Upvotes: 2

JKirchartz
JKirchartz

Reputation: 18022

Why not do:

$('#edit-search-block-form-1').focus(function(){
 if ($(this).val() == "Enter search keywords here"){
   $(this).val("");
 }
});
$('#edit-search-block-form-1').blur(function(){
 if ($(this).val() == ""){
   $(this).val("Enter search keywords here");
 }
});

It will keep the description in the box, as long as the box is "blank".

Upvotes: 5

Argiropoulos Stavros
Argiropoulos Stavros

Reputation: 9533

If plain javascript is good for you..

document.getElementById('ElementId').value='';

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

Try rearranging it like this:

$('#edit-search-block-form-l').click(function() {           
  if($(this).val() == 'Enter search keywords here') 
    $(this).val('');
});

This just prevents the user from searching for 'Enter search keywords here' specifically, but is that really an issue? Look up top on this page, type in "search", click out, then click the box again...would a user ever even notice it? probably not :)

The why it doesn't work part:
$('#block-search-0 #edit-search-block-form-l').attr('value', ''); will clear the value every time, you need an if to see if you actually want to clear :)

Upvotes: 7

Related Questions