I am trying to use a little jQuery to "hide" the initial value in a Google Search box when you click in the box and I am missing something.
Here is the search box code:
<div id="search_box">
<form action="http://mfrp.ehclients.com/search_results" id="cse-search-box">
<div>
<input type="hidden" name="cx" value="017425724926122041548:1ccj3d-e1-s" />
<input type="hidden" name="cof" value="FORID:9" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" id="q" name="q" value="Search..." size="31" />
</div>
</form>
<script type="text/javascript"开发者_如何学运维 src="http://www.google.com/cse/brand?form=cse-search-box&lang=en"></script>
</div>
Here is the jQuery:
<script type="text/javascript">
$('#q').click(function() {
if($(this).val() == 'Search...')
$(this).val('');
});
</script>
Only problem is, it doesn't work. Here is the page.
I would appreciate some help sorting this out.
Thanks,
Forrest
When your code it needs to run when the DOM elements available to find, so $("#q")
finds the id="q"
elements to bind to. This means your script either needs to run after the elements it needs in the page (e.g. end of the <body>
), or when the DOM is completely ready, like this:
$(function() {
$('#q').click(function() {
if($(this).val() == 'Search...')
$(this).val('');
});
});
If you're not doing this, and the $("#q")
selector doesn't find any elements...there's just nothing to run .click()
on, which binds that handler.
I think what you'll want is the reverse as well, which would look like this:
$(function() {
$('#q').focus(function() {
if($(this).val() == 'Search...') $(this).val('');
}).blur(function() {
if($(this).val() == '') $(this).val('Search...');
});
});
This will put "Search..." back in the box if it's empty and someone clicks outside, by relying on .focus()
and .blur()
instead of .click()
.
demo
You've been faked by google... the textbox has a background which look as if there was value... you should have checked that on the dev tools..
so just try to remove it on blur...
$('#q').blur(function(){
$(this).css('background','none');
if(this.value == '') {
this.value = this.defaultValue;
}
}).focus(function() {
if(this.value == this.defaultValue) {
this.value = '';
}
});
精彩评论