javascript simulates a button event to trigger an input box oninput event

Record to solve the problem that textarea does not take effect after js assignment

What I want to achieve is to simulate the input of a paragraph in the web chat box, and then js triggers the click to send event

However, after using js to assign directly, the textarea did not receive the value

document.querySelector('#id').value = 333;

insert image description here
I also thought of using key events to trigger onkeydown, onkeypress, and onkeyup, but it didn't work for a long time~

Finally, through the event listener, delete the events from the textarea to the upper level one by one.
finally! ! When deleting to input, the number of words will no longer change when inputting manually!
insert image description here
The next step is to trigger the input event

method 1:

This is suitable for hijacking setter events by frameworks, such as react vue

function changInputValue(inputDom,newText){
    
    
	let lastValue = inputDom.value;
	inputDom.value = newText;
	let event = new Event('input', {
    
     bubbles: true });
	event.simulated = true;
	let tracker = inputDom._valueTracker;
	if (tracker) {
    
    
  	tracker.setValue(lastValue);
	}
	inputDom.dispatchEvent(event);
}
 
//使用方法
var userIdDom = document.getElementById('userId');		//普通JS获取输入框Dom
changeReactInputValue(userIdDom,'username');			//改变React的输入框的值

Method 2 (directly trigger the input event):

document.querySelector('#id').dispatchEvent(new Event('input'));

Additional records of codes found when sending key events, the latest available

function fireKeyEvent(element, evtType, keyChar) {
		element.focus();
		var KeyboardEventInit = {key:keyChar, code:"", location:0, repeat:false, isComposing:false};
		var evtObj = new KeyboardEvent(evtType, KeyboardEventInit);
		element.dispatchEvent(evtObj);
	}
	
	var objInput = document.querySelector('#id');
	fireKeyEvent(objInput,"keydown","a11");
	```

Guess you like

Origin blog.csdn.net/a0405221/article/details/124374119