Stacked
Stacked

Reputation: 7336

Clear text with JavaScript in MVC 4

I've the following search box:

@Html.TextBox("SearchString", "search...", new { @class = "SearchTxtBox" })

A text box with a default text "search...", I want to clear the text when the user enters the text box like we do in pure html:

<input type="text" value="search..." onfocus="if(this.value=='search...') this.value='';">

Any ideas how to do so in MVC 4?

Upvotes: 0

Views: 1198

Answers (2)

PSL
PSL

Reputation: 123739

If you want to do the traditional way you cna do it this way:-

@Html.TextBox("SearchString", "search...", new { @class = "SearchTxtBox",onfocus="if(this.value=='search...') this.value='';" });

You can utilize HTML5 placeholder attribute too...

@Html.TextBox("SearchString","", new { @class = "SearchTxtBox", placeholder = "search..." });

Be aware of the fact that it is not supported in older browsers

If you want to know more about its support and workaround you can go through the below thread.

HTML5 "placeholder" support

Upvotes: 3

Sagar Hirapara
Sagar Hirapara

Reputation: 1697

you don't have to use javascript to clear default text of textbox,you can use property of Html5's PlaceHolder

Try this

@Html.TextBox("SearchString", new { @class = "SearchTxtBox" ,placeholder="search..."})

Upvotes: 1

Related Questions