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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With