jQuery jquery清除输入默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11755080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery clear input default value
提问by viktor
How can I clear the default value of an input form onfocus with jquery and clear it again when tha submit button is pressed?
如何使用 jquery 清除 onfocus 输入表单的默认值,并在按下提交按钮时再次清除它?
<html>
<form method="" action="">
<input type="text" name="email" value="Email address" class="input" />
<input type="submit" value="Sign Up" class="button" />
</form>
</html>
<script>
$(document).ready(function() {
//hide input text
$(".input").click(function(){
if ($('.input').attr('value') == ''){
$('.input').attr('value') = 'Email address'; alert('1');}
if ($('.input').attr('value') == 'Email address'){
$('.input').attr('value') = ''}
});
});
</script>
回答by Kaustubh
You may use this..
你可以用这个..
<body>
<form method="" action="">
<input type="text" name="email" class="input" />
<input type="submit" value="Sign Up" class="button" />
</form>
</body>
<script>
$(document).ready(function() {
$(".input").val("Email Address");
$(".input").on("focus", function() {
$(".input").val("");
});
$(".button").on("click", function(event) {
$(".input").val("");
});
});
</script>
Talking of your own code, the problem is that the attr api of jquery is set by
说到自己的代码,问题是jquery的attr api是由
$('.input').attr('value','Email Adress');
and not as you have done:
而不是像你所做的那样:
$('.input').attr('value') = 'Email address';
回答by Sasha
$(document).ready(function() {
//...
//clear on focus
$('.input').focus(function() {
$('.input').val("");
});
//clear when submitted
$('.button').click(function() {
$('.input').val("");
});
});
});
回答by DJ Forth
Unless you're really worried about older browsers, you could just use the new html5 placeholder
attribute like so:
除非您真的担心旧浏览器,否则您可以placeholder
像这样使用新的 html5属性:
<input type="text" name="email" placeholder="Email address" class="input" />
回答by Faust
$('.input').on('focus', function(){
$(this).val('');
});
$('[type="submit"]').on('click', function(){
$('.input').val('');
});
回答by tekilatexee
Try that:
试试看:
var defaultEmailNews = "Email address";
$('input[name=email]').focus(function() {
if($(this).val() == defaultEmailNews) $(this).val("");
});
$('input[name=email]').focusout(function() {
if($(this).val() == "") $(this).val(defaultEmailNews);
});
回答by Toni Michel Caubet
Just a shorthand
只是简写
$(document).ready(function() {
$(".input").val("Email Address");
$(".input").on("focus click", function(){
$(this).val("");
});
});
</script>