0
如果用户从选择输入中选择“是”,我有一个表单显示额外的字段。这些额外的字段都是必需的,除非用户选择'否',在这种情况下,字段被隐藏并且必需的属性被删除。它的工作原理,但我遇到了一个问题,如果用户选择“是”,然后恢复为“否”,那么表单将不会提交,大概是因为它没有删除必需的属性,仍然期望字段被填写。如果有人可以帮助解决这个问题,将不胜感激。HTML JavaScript - 带有额外/可选字段的表单的问题
HTML:
<form id="auth_form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<br>
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<label for="auth_code10" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required disabled>
<span class="form-control-feedback glyphicon" id="iconBad"></span>
</div>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
的JavaScript:
$(document).ready(function() {
$("#defect").on("change", checkIfYes);
// Functions
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
$('#auth_code_input').blur(function() { // validate the extra fields
if (!ValidateInput()) {
e.preventDefault();
}
});
$('#auth_form').on('submit', function(e) { // validate the extra fields
if (!ValidateInput()) {
e.preventDefault();
}
})
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
function ValidateInput() {
var code = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (code.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
});
完美,谢谢。 – sinesine
你欢迎我的朋友。 –