Adding default search text to search box html

大兔子大兔子 提交于 2019-12-08 06:45:29

问题


I am working on adding "search" text to a search box. I am trying to achieve:

onfocus: disappear text

And

onblur: reappear text

So far I have achieved this but i have had to hardcode it into html:

eg.

<input type="text" name="s" id="search-text" size="15" value="Search"  
onfocus="if (this.value==this.defaultValue)
this.value='';" onblur="if(this.value==''){this.value='Search'}">

And if I add this the of my .html file I am getting the same result:

eg.

<script type="text/javascript">
var defaultText = "Search...";
var searchBox = document.getElementById("search");

//default text after load
searchBox.value = defaultText;

//on focus behaviour
searchBox.onfocus = function() {
    if (this.value == defaultText) {//clear text field
        this.value = '';
    }
}

//on blur behaviour
searchBox.onblur = function() {
    if (this.value == "") {//restore default text
        this.value = defaultText;
    }
}
</script>

(courtesy: http://zenverse.net/javascript-search-box-show-default-text-on-load/)

What i am trying to achieve is using the above code in an external .js file but no matter what I do i cannot manage to back-link the code to my search box in my .html file.

I am sorry if this is a bad question I have made about 10 different .html and .js files swapping and remapping code and still can't get it to work without having the javascript in the actual .html file.

Any help would be much appreciated Thank You.


回答1:


Use the html5 placeholder property:

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

Here's a small Fiddle with the input element.

Notice that the text doesn't actually go away until the user enters some text, himself. This way, the user will see the hint longer.




回答2:


try using Html Placeholder

<input type="text" name="s" id="search-text" size="15" value="" Placeholder="Search" >

But you still want do it with javascript see the demo




回答3:


Might be useful to take a look at jQuery Placeholder for placeholder support in older browsers.




回答4:


Use below script it is working fine.

<script type="text/javascript">
 var defaultText = "Sitede ara…";
 var searchBox = document.getElementById("ctl00_ctl34_S52EF3DAB_InputKeywords");

 //default text after load
 searchBox.value = defaultText;

 //on focus behaviour
 searchBox.onfocus = function () {
     if (this.value == defaultText) {//clear text field
         this.value = '';
     }
 }



来源:https://stackoverflow.com/questions/14069301/adding-default-search-text-to-search-box-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!