How to Programmatically Force an Onchange Event on an Input

How do I programmatically force an onchange event on an input?

Create an Event object and pass it to the dispatchEvent method of the element:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.


By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.

If you want the event to bubble, you need to pass a second argument to the Event constructor:

var event = new Event('change', { bubbles: true });

Information about browser compability:

  • dispatchEvent()
  • Event()

Trigger onChange event manually

The simplest solution here would be to change the definition of your rootChange function to accept the value instead of the event itself.

const rootChange = value => { setRootSelect(value.split(',')); }

// In parent:
<Child onChangeSelect={rootChange}>

// Select
<NativeSelect ref={ref} onChange={(e) => onChangeSelect(e.target.value)}>

You can trigger the function manually with:

onChangeSelect(whateverValueYouWant); // notice that you need the brackets when calling the function.

Answer in Typescript

//Child Component
type PropsType = {
onChange: (value: string) => void;
value: string;
};
const CustomInput: FC<PropsType> = (props: PropsType) => {
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
props.onChange(event.target.value);
};
return (<input
onChange={onChange}
type="text"
value={props.value}></input>);
};

//Parent Component
const [input, setInput] = React.useState('');

<CustomInput
onChange={(value: string) => {
setInput(value);
}}
value={input}></CustomInput>

How can I trigger an onchange event manually?

There's a couple of ways you can do this. If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the HTML attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");

Javascript manually firing .onchange() event

The error about target is because there's code in the event handler that's trying to read the target property of the Event object associated with the change event. You could try passing in an faux-Event to fool it:

var range= document.getElementById('range');
range.onchange({target: range});

or, if you can, change the handler code to use this instead of event.target. Unless you are using delegation (catching change events on child object from a parent, something that is troublesome for change events because IE doesn't ‘bubble’ them), the target of the change event is always going to be the element the event handler was registered on, making event.target redundant.

If the event handler uses more properties of Event than just target you would need to fake more, or go for the ‘real’ browser interface to dispatching events. This will also be necessary if event listeners might be in use (addEventListener, or attachEvent in IE) as they won't be visible on the direct onchange property. This is browser-dependent (fireEvent for IE, dispatchEvent for standards) and not available on older or more obscure browsers.

Trigger Change event when the Input value changed programmatically?

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
$myInput.val('Another value');
$myInput.trigger('change');
};

how to trigger onChange event on text input when the value is changed programmatically - react

You can use componentWillReceiveProps hooks to achieve it, as your props get updated it will call componentWillReceiveProps method. Inside the method it is your playground. Please make sure this method will be called on each and every time the props changes

import React,{ Component } from 'react'

class InputBox extends Component {
componentWillReceiveProps(nextProps){
// write your logic here or call to the common method
console.log(nextProps.transcript);
}
handleChange(e){
console.log(e.target.value)
}
render(){
return(
<section>
<input
onChange={this.handleChange}
value={this.props.transcript}
type='text'
/>
</section>
);
}
}

export default InputBox;


Related Topics



Leave a reply



Submit