简体   繁体   中英

Input field, on focus, assign value, on blur keep value, on focus keep value

Here is what I'm trying to do:

I have a simple input field, if it has an empty value, on focus, I want to give it a value of 12345.
The issue is that once the value becomes 12345, and I put anything (eg 7890) after it, click ouside, click back inside, it removes the 7890.

http://jsfiddle.net/4VYpV/

How can I have the 7890 or anything after that act as the value so it does not get erased on blur and focus?

You had focus function bind and the check for a blank val swapped.

Try this:

EDIT: Updated the code to remove the redundant each function based on @karim79's comments

$('.inputField').focus(function() {
        if ($(this).val() == '') $(this).val("12345");
});

Working example: http://jsfiddle.net/4VYpV/1/

Like this ?

$('.inputField').each(function() {
  if($(this).val() == '')
    $(this).focus(function(){
      if($(this).val() == '')
      $(this).val("12345");
  });    
});

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