Reputation: 1329
I have a function that inserts a value into a hidden input. As soon as the input value changes because of my function I would like a variable to update.
I keep running into a couple errors. Either I get Object Object
as a response when I check the variable or the variable doesn't update unless I manually type in a value in the input then click out of the box.
var name = $('#name');
function updateVariable(nameTwo) {
name = nameTwo;
}
setTimeout(function() {
$('#name').val('John');
}, 1000);
$('button').click(function() {
$('#test').text(name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name" onchange="updateVariable(this.value)" />
<h1 id="test"></h1>
<button>Test</button>
Upvotes: 1
Views: 1297
Reputation: 11
your function does not have an s on the end like the call to it
updateVariable vs updateVariables
Upvotes: 1
Reputation: 21759
You almost had it, you have to select the value of the element, and you should trigger the change event also:
var name = $('#name').val();
function updateVariable(nameTwo) {
name = nameTwo;
}
setTimeout(function() {
$('#name').val('John').trigger('change');
}, 1000);
$('button').click(function() {
$('#test').text(name);
});
Upvotes: 2