2013-05-01 41 views
0

頁面上的我的文本框預先填充了所需的文本或「輸入文本」。預先填充的文本框值將消失onclick

如果框中有「輸入文本」,我希望這些文本在框上消失。但是如果沒有輸入任何內容,那麼文本框會返回到預填充的「輸入文本」。

如果紙箱與其他文本(除了「輸入文本」等人口,那麼我想它留爲是

這是我到目前爲止已經上了後臺代碼:

txtBox.Attributes.Add("onblur", "if(this.value='Enter Text') {this.value=''} else if(this.value.length<=0) {this.value='" + prepopulatedText.ToString() + "'} "); 

但它不工作。

任何想法?

我應該使用 「的onClick」,而不是太多?

+1

你有沒有聽說過的'placeholder'屬性? – Musa 2013-05-01 00:07:45

回答

0

如果您使用Winforms,則可以使用Enter event刪除文本。您可以將它們直接在編輯器中通過

txtBox.Enter += new System.EventHandler(Enter); 
txtBox.Leave+= new System.EventHandler(Leave); 

private void Enter(object sender, EventArgs e) 
{ 
    if (txtBox.Text == "Enter Text") 
    { 
     txtBox.Text = string.Empty; 
    } 
} 

而且Leave event把它放回去註冊,或。

private void Leave(object sender, EventArgs e) 
{ 
    if (txtBox.Text == string.Empty) 
    { 
     txtBox.Text = "Enter Text"; 
    } 
} 
1

如果你還沒有擔心舊瀏覽器,那麼你可以使用HTML5輸入屬性即。 placeholder

<input type="text" name="fisrtName" placeholder="Enter your name"> 

否則,你可以做這樣的

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

JS Fiddle

+0

謝謝薩欽。它不適用於我使用第二種方法(我們將使用舊版瀏覽器)。最終,如果文本框包含「輸入文本」,我只想讓文本框文本消失。我使用了以下代碼: txtBox.Attributes.Add(「onfocus」,「if(this.value =='Enter Text')this.value =''」); 但它仍然無法正常工作... – 2013-05-03 04:19:05