Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Jack Thor Avatar asked Nov 05 '25 14:11

Jack Thor


2 Answers

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;
}
like image 89
Praveen Kumar Purushothaman Avatar answered Nov 07 '25 05:11

Praveen Kumar Purushothaman


This is the current logic:

  1. Initialize a variable that has an undefined value.
  2. Bind a handler which is executed at undefined junctures, the variable is still undefined.
  3. Return the undefined value immediately

The above logic is broken and should be rectified. The best option is moving the final logic into the blur handler:

 $('.input').blur(function() {   
    var inputValue = this.value;
    // do something with the value
    // ...
 });

If you need to get the value at a certain juncture, query the DOM, select the element and get it's value.

like image 28
undefined Avatar answered Nov 07 '25 05:11

undefined



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!