Search code examples
javascriptjqueryeventsreturnonblur

Return value from input field with the jQuery blur function


Goal: User focuses input field. User writes a value in input field. When user is done and the input field isn't in focus anymore, save inserted value to a variable called 'inputFieldValue'. This is should be done invoking the function 'returnInputValue'.

html

<!DOCTYPE html>
<html>
    <head>
        <title>My test</title>  
    </head>
    <body>

        <input class="input" />

        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript" src="test.js"></script>

    </body>
</html>

test.js

function returnInputValue() {

    var inputValue;

    $('.input').blur(function() {   

        inputValue = $('.input').val();

    });

    return inputValue;

}

var inputFieldValue = returnInputValue();

When I call the variable inputFieldValue variable from the console after having inserted a value and focused out again, it is still 'undefined'.

Have I missed something?


Solution

  • The function you execute is an asynchronous function, i.e., it is based on the time after the input triggers a blur event. You need to either return it inside the blur event:

    function returnInputValue() {
        var inputValue;
        $('.input').blur(function() {   
            inputValue = $('.input').val();
            return inputValue;
        });
    }
    

    As suggested by some, even above code is not correct. The inputValue doesn't work as it always returns undefined.

    Or, set it up to directly access the last blurred value.

    var inputValue = "Not Blurred Yet!";
    $('.input').blur(function() {   
        inputValue = $('.input').val();
    });
    
    function returnInputValue() {
        return inputValue;
    }