I am trying to change the input text (total INR) of the input field in this page by doing:
$(".cKOnhg").last().attr('value', Math.random() * 100000);
When inspected the "value" attribute of the input changes to a random number, however it automatically changes back to 0 (or the number that was manually inputted) after few seconds.
I have tried trigger()
and the sendkeys plugin mentioned here: https://stackoverflow.com/a/13946504/82985
Nothing seems to work. Is it even possible on this page to change the input value exactly like how a human would do?
I'm trying to change the input values and auto-submit the form.
This page is using React under the hood. The problem when you try to programmatically set the value is that you only update the DOM, but the underlying React's state remains the same, so the DOM gets reset on the next render tick.
In order to correctly update the input value, use this code (you don't need jQuery at all):
function setNativeValue(element, value) {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
}
// Wait for the DOM to be fully rendered by React before doing anything
window.addEventListener("load", function() {
const el = Array.from(document.querySelectorAll('.cKOnhg')).pop();
setNativeValue(el, Math.random() * 100000);
el.dispatchEvent(new Event('input', { bubbles: true }));
});
Explanation: in order to trigger a value change in React, you have to bypass the custom value setter that is added by the framework on the HTMLInputElement
instance, which overrides the one from HTMLInputElement.prototype
(the native one). Once you've done that, emit an input
event to notify the framework that the value has changed, for correct taking into account by the framework.
More information about this: https://github.com/facebook/react/issues/10135