Last active
June 6, 2022 13:14
-
-
Save romaricpascal/4ac7161f0f2839a854bc0a218cc59535 to your computer and use it in GitHub Desktop.
Reset form element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Resets the value of a given form `element` to that originally set in the HTML. | |
* Allows for more targetted reset that a `form.reset()` as neither HTMLFieldsetElement | |
* nor the specific form controls API have a `reset()` method. | |
* | |
* Form elements can be accessed through: | |
* - `fieldset.elements` if your elements are wrapped within a fieldset | |
* - `ancestorElement.querySelectorAll('input,textarea,select')` | |
* - `form.elements` if you need specific filtering over the form fields | |
* | |
* @param element {HTMLElement} | |
* @return void | |
*/ | |
function reset(element) { | |
if (element instanceof HTMLInputElement) { | |
if (element.type == 'checkbox' || element.type == 'radio') { | |
element.checked = element.getAttribute('checked'); | |
} else { | |
element.value = element.getAttribute('value'); | |
} | |
} else if (element instanceof HTMLSelectElement) { | |
element.value = ( | |
element.querySelector('[selected]') || element.options[0] | |
).value; | |
} else if (element instanceof HTMLTextAreaElement) { | |
element.value = element.textContent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment