设置搜索字段的默认值 - 请帮助!

时间:2009-06-23 18:24:15

标签: javascript jquery textfield

我正在尝试为搜索字段设置默认值。我们的想法是,在用户点击它之前,搜索字段的值为“搜索”,然后它应为空。只要它是“空白”(以“搜索”作为值),它应该具有类“.blank”。

我试过这个

<input autocomplete="off" class="" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="" />

它到目前为止工作,但是当我加载网站时,该字段只是空的。我必须首先在字段内单击,然后在页面上的某个位置单击以使效果有效。

我想这与onBlur有关。有什么想法吗?

谢谢!

7 个答案:

答案 0 :(得分:4)

这被称为水印。请参阅http://digitalbush.com/projects/watermark-input-plugin/了解示例

答案 1 :(得分:3)

另一个想法是在输入类型中放置占位符: (注意这是HTML5。)

<input type=text placeholder="Default text here"/>

这样,文本字段将以灰色文本颜色显示:此处为默认文本。点击后,它将删除文本并将其替换为您当前的文本,当它被清空时,它会回来。

答案 2 :(得分:2)

只需给它默认值'搜索'硬编码,如

<input ... type="text" value="Search" />

答案 3 :(得分:2)

听起来你需要直接在输入标签中将初始值设置为Search,如下所示:

<input autocomplete="off" class="blank" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="Search" />

请注意,我们也将初始类设置为blank

答案 4 :(得分:1)

我发现了问题,我的错误:当用户点击其他地方时,会调用onBlur。 onLoad仅允许使用标签BODY和FRAMESET。解决方案是在服务器端设置默认值(对于我在application_controller中,如果没有提交搜索词)。

非常感谢!

答案 5 :(得分:0)

模糊是当一个场失去焦点时,它无法松开焦点,直到焦点开始为止,因此你需要点击该字段,然后点击以查看它是否有效。你有没有试过默认将类设置为.blank?

<input autocomplete="off" class="blank" ....

答案 6 :(得分:0)

这是我用来执行此操作的代码段。可能有更简单的方法,但这是有效的。任何带有.cleardefault类的项目都会在第一次鼠标悬停时清除它的值。任何具有.setcleardefault类的项目都将清除默认值,如果用户未在框中放置任何内容,则在鼠标移出时将其重置为默认值。

function ClearDefault(item) {
    // clear the default value of a form element
    if (item.defaultValue == undefined)
        item.defaultValue = item.value;
    if (item.defaultValue == item.value)
        item.value = '';
} // ClearDefault

function SetDefault(item) {
    // if item is empty, restore the default value
    if (item.value == '')
        item.value = item.defaultValue;
} // SetDefault

$(document).ready(function() {
    $(".cleardefault")
        .mouseover(function(){
            ClearDefault(this);
        })
    $(".setcleardefault")
        .mouseover(function(){
            ClearDefault(this);
        })
        .mouseout(function(){
            SetDefault(this);
        });
    /*
    */
});