Skip to content

Instantly share code, notes, and snippets.

@siwalikm
Last active February 1, 2019 10:15
Show Gist options
  • Save siwalikm/2582ebbc42192ec8a0d02df74eea0f10 to your computer and use it in GitHub Desktop.
Save siwalikm/2582ebbc42192ec8a0d02df74eea0f10 to your computer and use it in GitHub Desktop.
Trigger React's synthetic change events on input, textarea and select elements
function reactTriggerChange(e){var t,n,c,r,a,i,v,u,o,d,l=e.nodeName.toLowerCase(),p=e.type;function s(e,t){var n=Object.getOwnPropertyDescriptor(e,t);n&&n.configurable&&delete e[t]}function E(e){e.preventDefault(),r||(e.target.checked=!1),a&&(a.checked=!0)}"select"===l||"input"===l&&"file"===p?((t=document.createEvent("HTMLEvents")).initEvent("change",!0,!1),e.dispatchEvent(t)):"input"===l&&{color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0}[p]||"textarea"===l?(n=Object.getOwnPropertyDescriptor(e,"value"),(t=document.createEvent("UIEvents")).initEvent("focus",!1,!1),e.dispatchEvent(t),"range"===p?(v=(i=e).min,u=i.max,o=i.step,d=Number(i.value),i.min=d,i.max=d+1,i.step=1,i.value=d+1,s(i,"value"),i.min=v,i.max=u,i.step=o,i.value=d):(c=e.value,e.value=c+"#",s(e,"value"),e.value=c),(t=document.createEvent("HTMLEvents")).initEvent("propertychange",!1,!1),t.propertyName="value",e.dispatchEvent(t),(t=document.createEvent("HTMLEvents")).initEvent("input",!0,!1),e.dispatchEvent(t),n&&Object.defineProperty(e,"value",n)):"input"===l&&"checkbox"===p?(e.checked=!e.checked,(t=document.createEvent("MouseEvents")).initEvent("click",!0,!0),e.dispatchEvent(t)):"input"===l&&"radio"===p&&(r=e.checked,a=function(e){var t,n,c=e.name;if(c)for(t=document.querySelectorAll('input[type="radio"][name="'+c+'"]'),n=0;n<t.length;n+=1)if(t[n].checked)return t[n]!==e?t[n]:null;return null}(e),n=Object.getOwnPropertyDescriptor(e,"checked"),e.checked=!r,s(e,"checked"),e.checked=r,e.addEventListener("click",E,!0),(t=document.createEvent("MouseEvents")).initEvent("click",!0,!0),e.dispatchEvent(t),e.removeEventListener("click",E,!0),n&&Object.defineProperty(e,"checked",n))}
// minified and altered from https://unpkg.com/[email protected]/lib/change.js
// usage: reactTriggerChange(dom_node_to_trigger)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment