Значение по умолчанию для jquery clear input
Как я могу удалить значение по умолчанию для входной формы onfocus с помощью jquery и очистить его снова, когда нажата кнопка отправки?
<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>
Ответы
Ответ 1
Вы можете использовать это.
<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>
Говоря о вашем собственном коде, проблема в том, что attr api jquery задается
$('.input').attr('value','Email Adress');
а не так, как вы это сделали:
$('.input').attr('value') = 'Email address';
Ответ 2
$(document).ready(function() {
//...
//clear on focus
$('.input').focus(function() {
$('.input').val("");
});
//clear when submitted
$('.button').click(function() {
$('.input').val("");
});
});
Ответ 3
Если вы действительно не беспокоитесь о старых браузерах, вы можете просто использовать новый атрибут- placeholder
html5 следующим образом:
<input type="text" name="email" placeholder="Email address" class="input" />
Ответ 4
$('.input').on('focus', function(){
$(this).val('');
});
$('[type="submit"]').on('click', function(){
$('.input').val('');
});
Ответ 5
Попробуйте следующее:
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);
});
Ответ 6
Просто сокращенное
$(document).ready(function() {
$(".input").val("Email Address");
$(".input").on("focus click", function(){
$(this).val("");
});
});
</script>