I have a form on a page with multiple inputs. I want to handle events if someone put anything to my form by code in browser console(or browser extension or browser automation tools like puppeteer).
e.g. Code that changes value in a form and I want to be able to get some event when value of my input
element is changed.
let element = document.querySelector('#test');
element.value = 'x';
I expect that this code should cause some event/mutation that I can handle. But nothing is triggered. I haven't find any event that is triggered and mutation on attribute change also doesn't work.
The strange thing is that when input value is changed by element.value = 'x'
, mutation is not triggered. But when setAttribute
is used everything works fine element.setAttribute('value', 'x')
My code:
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation) {
console.log('Mutation happened');
let observer = document.querySelector('#observer');
observer.value = 'Mutation happened';
}
});
});
let element = document.querySelector('#test');
observer.observe(element, { attributes: true });
//Setting value by using setAttribute API causes mutation
//element.setAttribute('value', 'a');
//Setting value by using `.value` API does not cause mutation
element.value = 'b';
Input field: <input id='test' onInput='console.log(1)'/><br/>
Does mutation happen? <input id='observer' value='Mutation did not happen'/>
How to catch changing of value of HTML input by Javascript code?
It should not be necessary MutationObserver
. Any option will be fine.