2013-04-02 84 views
0

嗨,我有這個輸入字段jQuery的輸入字段值切換

<form action="" method="post"> 
    <input type="text" value="Type Your Email" name="field" class="field"/> 
    <input type="submit" value="Submit" class="submit" /> 
</form> 

林triying顯示/隱藏的價值,當我點擊領域。問題是,我忘了如何達到我試過的價值

$('.field').click(function(){ 

    $('.field value').toggle(); 

}); 

但它不工作。

回答

3

你不能顯示或隱藏字段值,但你可以設置它。

你可能會尋找這樣的事情:

$('.field').focus(function(){ 
    if($(this).val() == 'Type Your Email') { 
     $(this).val(''); 
    } 
}).blur(function() { 
    if($(this).val() == '') { 
     $(this).val('Type Your Email'); 
    } 
}); 

以上,該值被設置focusblur,而不是在單擊時場,這樣的代碼,當你訪問仍然有效該字段通過tab或其他方式。但是,我寧願將您的注意力吸引到html5屬性placeholder,這確實如此,但沒有一些不良的副作用(例如,您的字段的value永遠不會成爲佔位符文本)。

+1

'您的字段的值永遠不會佔位符文本,例如'。從來沒有聽說過這個。我總是在SO學習新東西。 +1。我不能重現它。你能製作一個小提琴嗎? – Jashwant

+0

@Jashwant:是的,這就是佔位符的作用([demo](http://jsfiddle.net/mYPa5/))。它不是一個正在設置和取消設置的值,它僅僅是一串在沒有值的情況下顯示的文本。 –

+0

正如Jashwant所說,「佔位符」是這種情況下最好的實踐。 +1佔位符' – tiagojpdias

0

Demo

Placeholder attribute將是你的問題的最佳解決方案,但請注意

佔位符屬性,在Internet Explorer 10, 火狐,歌劇,鉻,和Safari支持。 注意:Internet Explorer 9和更早版本不支持標記的佔位符屬性。

$('.field').on('focus',function(){ 

if($(this).val() == 'Type Your Email') { 
     $(this).val(''); 
    } 

}); 

$('.field').on('blur',function(){ 
    if($(this).val() == ""){ 
    $(this).val("Type Your Email"); 
    } 
}); 
0

我想你問的是這個

$('.field').on("focus", function() { 
    var txt = $(this); 
    if (txt.val() == "Type Your Email") 
     txt.val(""); 
}); 

$('.field').on("blur", function() { 
    var txt = $(this); 
    if (txt.val() == "") 
     txt.val("Type Your Email"); 
}); 

或者你可以使用Placeholder屬性(但它不能在IE瀏覽器)

<input type="text" value="Type Your Email" 
     name="field" class="field" 
     placeholder="Type Your Email"/> 
1

你可以使用「佔位符」

你會給裏面什麼將在文本字段中顯示的佔位符屬性 如果您專注於將隱藏的文本字段。如果你注重了與輸出類型,將顯示佔位符值

例子:

<form action="post"> 
    <input type="text" name="fname" placeholder="First name"><br> 
    <input type="text" name="lname" placeholder="Last name"><br> 
    <input type="submit" value="Submit"> 
</form> 
0

您可以使用純JS

<input type="text" value="Type Your Email" onfocus="this.value=''" onblur="this.value='Type..'"  name="field" class="field"/> 

$(".field").focus(function(){ $(this).val='';}); 
$(".field").blur(function(){ $(this).val='Type something';}); 

這是好習慣在進行更改之前檢查輸入是否有價值,以便不清楚用戶輸入的字段。

更多信息,你可以找到 http://api.jquery.com/focus/http://api.jquery.com/blur/

0

試試這個http://jsfiddle.net/zander_pope/udu5cchh/

$(function() { 
    $('.button').on('click', function (e) { 
     if (!$('.dd').val()) { 
      $('.dd').val("relevance"); 
     } else { 
      $('.dd').val(""); 
     } 
    }); 
}); 
$(function() { 
    $('.button').on('click', function (e) { 
     $('.search').click(); 
    }); 
}); 

希望它能幫助!