Using jQuery to auto select text in a field
So you've custom themed a search bar into your brand spanking new custom theme using my handy tutorial covering that topic (http://www.agaricdesign.com/note/theme-search-form-drupal-6)
Now you've noticed that when you click in the actual search field provided, the "search text here" which is the default value does not auto select. This means the user will have to delete the default value before they can enter their own search terms. This means nothing to most, but apparently if you are a perfectionist you just can't let it go.
Fear not! Thanks to jQuery, we can auto select that text, and easily too. All you have to do is create a js file with the code below and include it in your theme's info file.
if (Drupal.jsEnabled) {
$(document).ready(function() {
$('input[name=search_theme_form]').focus(function()
{
$(this).select();
});
});
}
** the code above assumes your input field name is 'search_theme_form' (which it will be if you've made it using my other awesome tutorial on theming search)
That's it!, don't forget to clear cache, or resave your themes page.
Here's some more info:
Let's say this is the code being output for the search bar... well, at least the text field part of it
<input type="text" class="form-text cleardefault" value="search text here" size="15" id="edit-search-theme-form-1" name="search_theme_form" maxlength="128"/>
Now if you sit there for a really really long time and study the code snippets above, you will hopefully start to see the relation.
$('input[name=search_theme_form]') calls <input ...... name="search_theme_form">
and this concludes our lesson on using jQuery to auto select the default value of your search bar text.
now go do it! and know in your heart that the Agaric Way will always guide you.....
Comments
This is the updated better version
Drupal.behaviors.exampletheme = function (context) { $('#search-box input[value]').focus(function() { $(this).select(); }); };
brought to you by the agaric night crewExplanation of Selecting input field content
Hi Dan, thanks for doing this for drupal. I also would recommend read this article about selecting input field with jquery to users how would like to know more about the insights. It explains the details of the code, etc.
Just my 2 cents.
Post new comment