I've got an input
with google autoComplete
connected.
When the user moves up and down through the seachResults
the value of the input is changed dynamically via JavaScript.
I'd like to capture the value that is in the input at any given time.
I've tried onChange
and onInput
but since no event is getting fired, and the value
of the DOM Node
is not getting set - there are no updates.
How do you detect changes to the input
that are dynamically updated via JavaScript
?
The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event.
The input event triggers every time after a value is modified by the user. Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
How it works: First, select the <input> element with the id message and the <p> element with the id result . Then, attach an event handler to the input event of the <input> element. Inside the input event handler, update the textContent property of the <p> element.
The .value
attribute will only change if the script-writer has called setAttribute('value'
to set the new value, which is quite an odd thing to do. In almost all situations, I would expect the value to be set by assigning to the value
property directly, eg:
input.value = 'foo';
Calling setAttribute
will indeed show a change in the inspected DOM attribute, eg:
<input value="somevalue">
const input = document.querySelector('input');
input.setAttribute('value', 'foo');
console.log(input.outerHTML);
<input>
But just assigning to the .value
property of the element will not result in such a change:
const input = document.querySelector('input');
input.value = 'foo';
console.log(input.outerHTML);
<input>
Assigning to the .value
actually invokes a setter function on HTMLInputElement.prototype
:
console.log(HTMLInputElement.prototype.hasOwnProperty('value'));
You can shadow this by putting a getter/setter for value
directly on the element itself, with the setter invoking your own function, allowing you to listen for changes:
const { get, set } = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
const input = document.querySelector('input');
Object.defineProperty(input, 'value', {
get() {
return get.call(this);
},
set(newVal) {
console.log('New value assigned to input: ' + newVal);
return set.call(this, newVal);
}
});
// example of autocomplete trying to change the input value:
input.value = 'foo';
<input>
Consider creating and triggering input events
var event = new Event('input', {
bubbles: true,
cancelable: true,
});
then
myelement.dispatchEvent(event);
more info
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