Luke
Luke

Reputation: 3551

"Mimic" placeholder attribute in jQuery?

Background

I've got a couple of jQuery functions that set a search field to contain the word "Search" and clear it / reset it when the field is clicked in and out of....

// Search Box Placeholder
jQuery('#q').focus(function() {
            if(jQuery(this).val() == 'Search') {
                jQuery(this).val('');       
            }
            else if(jQuery(this).val() == '') {
                jQuery(this).val('Search');
            }
        });
jQuery('#q').blur(function() {
            if(jQuery(this).val() == '') {
                jQuery(this).val('Search');             
            }
        });
jQuery('#q').val('Search');

Question ?

The only issue is I'm not sure how to clear the word Search if the search form is submitted without an alternative search term being set. Is there a way to check and clear the contents before the form submission if the contents are equal to 'Search' ?

Upvotes: 1

Views: 205

Answers (3)

Spudley
Spudley

Reputation: 168843

The key to finding the answer to this kind of thing is often more about knowing the terminology than anything else.

In this case, if you'd searched for the word "polyfill" rather than "mimic", you'd have found the solution. "Polyfill" is web developer speak for a browser script that implements a feature of newer browsers so that it works in older browsers.

The placeholder feature is a classic one for this, because it's very useful and easily done.

Modernizr is a Javascript library that aims to simplify the process of working with polyfills. It detects whether a feature is supported, so that you can know whether or not to load the polyfill for that feature.

It's a useful tool, but the main reason I mention Modernizr is because they also maintain a big list of polyfill scripts.

Click that link and search for 'placeholder'... you'll find there's a whole stack of scripts that can do it for you. Just pick the one that works best for you, or crib from the techniques they use.

Hope that helps.

Upvotes: 1

Ram
Ram

Reputation: 144739

You can prevent the submission of form if the value is equal to 'Search'.

$('form').on('submit', function(){
   return $('#q').val() !== 'Search';
});

If you want to support older browsers that do not support placeholder attribute, you can also use a plugin.

https://github.com/parndt/jquery-html5-placeholder-shim

Upvotes: 2

DanC
DanC

Reputation: 8825

An alternative you may want to consider is not adding the placeholder text as the value of the control. Instead, use another element, possibly the input label or a span, absolutely positioned over the text input, and hide it when the corresponding input has the control. Also, when the user clicks on this label, you should hide it and set the focus to the control. This will also let you change the placeholder color.

Upvotes: 0

Related Questions