Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - set input value to previous value on blur if empty

Tags:

jquery

blur

I've spent a couple of hours on this and couldn't find anything to help so have thrown in the towel. I am simply trying to restore the previous value of an input box if the user clears it out and leaves nothing when the input loses focus. So for example, if it says "Brisbane, Australia" in my input box, and the user removes that text from the input and then presses tab, I want it to revert the input back to "Brisbane, Australia". Here is my code:

$('input#search-location').on("focus", function() {
  $(this).data("previous-value", $(this).val());
}); 

$('input#search-location').on("blur", function() {
  if ($(this).val() == "") {
    // alert($(this).data("previous-value"));
    $(this).val($(this).data("previous-value"));
  }
}); 

Both events fire, and if I uncomment the alert in the blur function, it correctly displays the previous value. But nothing appears in my input box, and no errors in the console. I guess it's something silly I'm missing... I appreciate any help!

like image 948
mchapman17 Avatar asked Jan 22 '26 13:01

mchapman17


1 Answers

Your code should work and does here Live Demo

Note you need to execute your code after the page elements have rendered, so you need to wrap the code in

$(function() { ... });

Alternative if you want to set it to the default value it had when the page loaded, try

Live Demo

$('input#search-location').on("blur", function() {
  if ($(this).val() == "") {
    $(this).val(this.defaultValue);
  }
});

Newer browsers will give a hint here:

<input placeholder="Type your name" />

and you can help older browsers support it

$(function() {
  if (!placeholderIsSupported) {
    $('#search-location1')
    .val($('#search-location1').attr("placeholder"))
    .on("blur", function() {
      if ($(this).val() == "") {
        $(this).val($(this).attr("placeholder"));
      }
    })
    .on("focus",function() {
      if ($(this).val()==$(this).attr("placeholder")) $(this).val("");
    });
  }  
});

function placeholderIsSupported() {
 var test = document.createElement('input');
 return ('placeholder' in test);
}
like image 171
mplungjan Avatar answered Jan 24 '26 02:01

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!