简体   繁体   中英

HTML 5 validates required input field with display none property and not submitting the form

I have a Form. All the fields in that form are required. But some fields are display:none by default and it will only display according to the selection of some dropdown boxes

<form class="form" name="my_form" id="my_form">
    <div id="dd">
        <label> Type*</label></div>
    <div class="input"><select onchange="show(this.value);" class="uk-width-1-1 uk-form-large" id="firmType"
                               name="firmType" required>
        <option value="">Select</option>
        <option value="Company">Company</option>
        <option value="Individual">Individual</option>
    </select>

    </div>
    <div class="uk-form-row" id="show" style="display:none;">
        <div id="label">
            <label> Name*</label></div>
        <div class="input"><input class="uk-width-1-1 uk-form-large" id="proprietorName" name="proprietorName"
                                  type="text" value="" placeholder="" required></div>
        <div id="label" class="right">
            <label> Company Reg. No*</label></div>
        <div class="input">
            <input class="uk-width-1-1 uk-form-large" id="agentRegNumber" name="agentRegNumber" type="text" value=""
                   placeholder="" required>

        </div>
    </div>
    <div class="uk-form-row">
        <input type="submit" class="uk-width-1-1 uk-button uk-button-primary uk-button-large AddAgent-button"
               name="AddAgent" id="AddAgent" value="Sign Up"/>
    </div>
</form>

function is given below.

function show(val) {
    if (val == 'Company') {
        document.getElementById("show").style.display = "block";
    } else {
        document.getElementById("show").style.display = "none";
    }
}

If I have selected Type as Individual, name and reg no field will not display. but while submitting form it is not submitting since that fields are required.

Remove required attribute when fields are not displayed:

function show(val) {
    if (val == 'Company') {
        document.getElementById("show").style.display = "block";
        setRequired(true);
    } else {
        document.getElementById("show").style.display = "none";
        setRequired(false);
    }
}

function setRequired(val){
    input = document.getElementById("show").getElementsByTagName('input');
    for(i = 0; i < input.length; i++){
        input[i].required = val;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM