Search code examples
javascriptjqueryinputfocusonblur

How to make JavaScript find value of input on focus, clear if it's default and keep if it's new data?


I've spent too many hours trying to figure this, and I've found parts of the answer here on Stackoverflow but still can't get this working.

What I want to do is control all input elements sitewide with some JS/jQuery. When a user focuses on the input, if the value is the same as when the page loaded, clear it, if it's been altered, keep it. Then on blur, if the field is empty, return the default value.

What I have so far is this:

var input = document.getElementsByTagName('input');

$('input, textarea').focus(function() {
    value = $(this).val();

    for (var i=input.length-1; i >= 0; i--) {           
        if(value == input[i].value){
            $(this).attr("value","");   
        }   
    }
});
$('input, textarea').blur(function() {
    if($(this).val()=="") {
        $(this).val(value);
    }
});

This partly works, it just keeps clearing the inputs though, whether they have been changed or not. I'm guessing I am storing the initial values wrong.


Solution

  • this line is the bad guy

    if(value == input[i].value){
    

    since getElementsByTagName returns a HTMLCollection, changes to the dom are also in your input variable. Thus, value will always be input[i].value, since your getting the value of the same input elem, which of course are the same!

    use jquery data method to save the value within the element. and on blur, retrieve it again to make the comparison.

    like this;

    var handlers={
        focus: function() {
            var elm=$(this),
                value=elm.val(),
                old=elm.data("placeholder");
            if (typeof old==="undefined"){
                elm.data("placeholder", value);
                old=value;
            }
            if (old==value){
                elm.val("");
            }
        },
        blur:function() {
            var elm=$(this);
            if( elm.val() == "" ) {
                elm.val( elm.data("placeholder") );
            }
        }
    };
    $('input, textarea').each(function(i, elem){
        $(elem).
            focus(handlers.focus).
            blur(handlers.blur);
    });
    //not tested, should work!