简体   繁体   中英

Input field value refill if empty after on focus

So i'm working on a form. When you focus (click) the text field, the value becomes blank. Now i want the default value to re-appear if the user hasn't filled in anything.

So for instance i have a text field with ID Question1. This is what works for the clear on focus.

 $(document).ready(function() { $("#Question1").val('Naam *'); $("#Question1").focus(function() { $("#Question1").val(''); }); }); 

Any javascript code for that?

Edit: I can't use placeholders because of CMS restrictions (concrete5). The text fields are generated.

You can do something like this with the help of blur() event

 $(document).ready(function() { var temp = 'Naam *'; $("#Question1").focus(function() { if (temp == this.value) // ------^-- empty the field only if the field value is initial this.value = ''; // emptying field value }).blur(function() { if (this.value.trim() == '') // -----^-- condition field value is empty this.value = temp; // if empty then updating with initial value }).val(temp); //----^-- setting initial value }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" id="Question1" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM