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?
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;
}
This is the current logic:
undefined value.undefined.undefined value immediatelyThe 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.
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