Mr.Smithyyy Mr.Smithyyy - 6 months ago 18
jQuery Question

JavaScript onchange update variable as soon as text value input changes

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>




Answer

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);
});