Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery clear input default value

Tags:

jquery

How can I clear the default value of an input form onfocus with jquery and clear it again when tha submit button is pressed?

<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> 
like image 685
viktor Avatar asked Aug 01 '12 08:08

viktor


People also ask

How do you clear a field in Javascript?

To clear an input field after submitting:Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.


2 Answers

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

$('.input').attr('value','Email Adress'); 

and not as you have done:

$('.input').attr('value') = 'Email address'; 
like image 160
Kaustubh Avatar answered Sep 17 '22 18:09

Kaustubh


$(document).ready(function() {   //... //clear on focus $('.input').focus(function() {     $('.input').val(""); });    //clear when submitted $('.button').click(function() {     $('.input').val(""); }); 

});

like image 26
Sasha Avatar answered Sep 16 '22 18:09

Sasha