Skip to content
Advertisement

get all child element of a form in J.S

how can i get all child element(like radio,checkbox,select,text,…) within a form and make them blank using javascript. My form has many other elements like table,div etc. but i dont want to changes on these other element.

Any suitable idea to get these child element(form element) through the form name(frmlist) or form id(frmlist) and make them blank. Actually i have no idea previously that how many elements are there in form and what are the names/ids of these element.

Thanks a lot…

Advertisement

Answer

Try something like this:

Example Form:

<form name="data_entry" action="#">
    Company Name: <input type="text" name="company_name">
    Select Business Type: <input type="radio" name="business_category" value="1"> Manufacturer
    <input type="radio" name="business_category" value="2"> Whole Sale Supplier
    <input type="radio" name="business_category" value="3"> Retailer
    <input type="radio" name="business_category" value="4"> Service Provider
    Email Address: <input type="text" size="30" name="email">
    Keep Information Private: <input type="checkbox" name="privacy">
    <input type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();">
    <input type="button" name="clear" value="Clear Form" onclick="clearForm(this.form);">
</form>

Example Javascript:

for (i = 0; i < frm_elements.length; i++) {
    field_type = frm_elements[i].type.toLowerCase();
    switch (field_type) {
    case "text":
    case "password":
    case "textarea":
    case "hidden":
        frm_elements[i].value = "";
        break;
    case "radio":
    case "checkbox":
        if (frm_elements[i].checked) {
            frm_elements[i].checked = false;
        }
        break;
    case "select-one":
    case "select-multi":
        frm_elements[i].selectedIndex = -1;
        break;
    default:
        break;
    }
}

From Using Javascript to Reset or Clear Form.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement