I have a bit of jQuery I have been using to set default text in a search box, remove the text when the user enters the search box, and then adds the text again if the search box loses focus. The code is as follows:
//global vars
var searchBox = jQuery("#plc_lt_mpHeaderContent_SiteSearch_txtWord");
var searchBoxDefaultText = "Keyword, Title, Name";
searchBox.val('Keyword, Title, Name');
//searchbox show/hide default text if needed
searchBox.focus(function ()
{
if (jQuery(this).attr("value") == searchBoxDefaultText) jQuery(this).attr("value", "");
});
searchBox.blur(function ()
{
if (jQuery(this).attr("value") == "") jQuery(this).attr("value", searchBoxDefaultText);
});
This code is launched in the jQuery(document).ready(function ()). The issue is that this works as expected in jQuery 1.4.2, but when I try the same code in jQuery 1.6.2 it does not work. I am wondering what I need to do to get it to be compliant with开发者_StackOverflow中文版 1.6.2. Any help is greatly appreciated.
Thank you
Jquery 1.6 update changed how attr works. Now you have to use prop instead. Release notes here http://blog.jquery.com/2011/05/03/jquery-16-released/
Even better would be to use .val(), like this:
searchBox.focus(function ()
{
if (jQuery(this).val() == searchBoxDefaultText) jQuery(this).val("");
});
searchBox.blur(function ()
{
if (jQuery(this).val() == "") jQuery(this).val(searchBoxDefaultText);
});
change the .attr() to .val()
searchBox.focus(function ()
{
if ($(this).val() == searchBoxDefaultText)
{
$(this).val();
}
});
searchBox.blur(function ()
{
if ($(this).val()=="")
{
$(this).val(searchBoxDefaultText);
}
});
Usually, you say jQuery(this).val("")
instead of jQuery(this).attr("value", "")
-- whether that's your problem, I don't know.
Instead of jQuery(this).attr("value"), I would use:
jQuery(this).val(); // for getting value
jQuery(this).val(searchBoxDefaultText); // for setting value
That said, I'll also recommend you look into HTML5's placeholder attribute (for compatible browsers), and then adding jQuery.hint (or any of the many similar plugins) for non-HTML5 browsers. Don't reinvent the wheel.
精彩评论