2013-08-29 22 views
1

我有2個輸入:如何首次清除焦點上的輸入?

<input type="text" value="username"> 
<input type="password" value="password"> 

我想刪除默認值(只是第一次),如果我在一個特定的輸入來的。我用這樣的JavaScript添加屬性如下:

onfocus="this.value='';" 

但是這個清楚了每次輸入的注意力。如何清除輸入只是第一次關注它呢?

+3

您想要的是稱爲佔位符。 –

+0

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-placeholder – j08691

回答

8

你想叫一個佔位符什麼:即自動刪除默認值。如果你需要兼容IE9,使用one of the many polyfills,人照顧的實施細節爲你

<input type="text" placeholder="username"> 

如果你能接受你的佔位符爲not visible for IE9- users,做到這一點。

1

嘗試

onfocus="if(this.flag == undefined){ this.flag = true; this.value=''; }" 
5

只需使用佔位符輸入,例如

<input type="text" placeholder="username"> 

這是很好的給出名稱對於每個輸入,所以:

<input type="text" name="username" placeholder="username"> 
+0

+1佔位符 – Anand

+0

爲什麼在AJAX時代給一個名字好?我認爲在過去三年中我的投入都沒有名字。 –

0

嘗試這樣的: -

$('.text').focus(function() { 
    if (this.value == this.value) { 
     $(this).val(""); 
    } 
}).blur(function() { 
    if (this.value == "") { 
     $(this).val(this.value); 
    } 
}); 

http://jsfiddle.net/32Tns/296/

0

只要把檢查您的onfocus功能

onfocus="if(this.value == 'username'){this.value='';}" 


<input type="text" value="username" onfocus="if(this.value == 'username'){this.value='';}"> 
    <input type="password" value="password" onfocus="if(this.value == 'password'){this.value='';}"> 

JSFIDDLE EXAMPLE

0
<input type="text" value="username" id="username" title="username" /> 

$('#username').bind({ 
    'focus': function(event) { 
     $(this).val(''); 
    }, 
    'blur': function(event) { 
     var obj = $(this), 
      title = obj.attr('title'); 
     obj.val(title); 
    } 
}) 
0

如果你使用jQuery,您可以使用此:

<input type="text" name="username" value="username" /> 

的Javascript:

$('input[name=username]').one('focus', function() { 
    $(this).val(''); 
}); 

.one()只會觸發綁定事件一次