我有一张表格。该表单中的所有字段都是必需的。但是某些字段是显示的:默认情况下为none,它只会根据某些下拉框的选择显示
<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 show(val) {
if (val == 'Company') {
document.getElementById("show").style.display = "block";
} else {
document.getElementById("show").style.display = "none";
}
}
如果我选择了Type as Individual,则不会显示name和reg no字段。但是在提交表单时,由于需要这些字段,因此无法提交。
答案 0 :(得分:4)
在未显示字段时删除required
属性:
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;
}
}