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");
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>
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.
onChange() is not a function. Trigger onChange() manually
If that is react you should not access the Dom for those kind of stuff. They have one Api to give you what you need.
You want one uncontroller component. In order to do that you can use one reference.
I havent tried but i think you can do this.
Create the ref on the constructor
this.inputRef = React.createRef();
Then assign the input ref prop to this.inputRef
<input ref={this.inputRef} id='example' type="file" accept="image/*" onChange={this.onImageChange} />
And lately dispatch the click.
this.inputRef.current.click();
Hope it works
How can I trigger a change event manually?
Try this
$('select#BrandNames').trigger('change');
or
var event = jQuery.Event('change');
event.target = $(document).find('select#BrandNames').get(0);
$(document).trigger(event);
Example
Trigger "onchange" event
The vast majority of the time, you don't want an event to be fired when you change the value with code. In those cases where you do, you can fire a synthetic event on modern browsers via dispatchEvent
. More here.
So in your specific example:
input.value = "Another example";
var event = document.createEvent("UIEvents"); // See update below
event.initUIEvent("change", true, true); // See update below
input.dispatchEvent(event);
Live demo
Update: As Benjamin noted, since the above was written, initUIEvent
has been replaced with the UIEvent
constructor, so that would be:
input.value = "Another example";
var event = new UIEvent("change", {
"view": window,
"bubbles": true,
"cancelable": true
});
input.dispatchEvent(event);
Live demo
Alternately, you can always just call whatever function you've bound to the change
event directly, which is usually what I'd do. But sometimes you want to use actual events (for instance, when using the observer pattern) and ensure that anyone who is listening for the change is notified.
Related Topics
How to Pass Model Data in JavaScript
Moment Js Get First and Last Day of Current Month
How to Save Binary Buffer to Png File in Nodejs
How to Close Toggle Menu When Clicking Navigation Item Anchor Link
Clear an Input Field With Reactjs
Regex With Space and Letters Only
How to Convert File to Base64 in JavaScript
How to Append Value to an Array Only If Not Exists and Remove It If Not
Wait for Asynchronous Functions to Finish in Angular
Add Two Numbers and Display Result in Textbox With JavaScript
Jquery Ajax Post Results in 500 Internal Server Error
How to Mock Private Functions With Jest
How Could I Get the Latest Date from an Array of Dates - Javascript/Typescript
Ngx-Datatable Set Column Width Dynamically