【发布时间】:2021-04-03 01:43:16
【问题描述】:
我在一个页面上显示了多个动态表单。请参阅下面的我的 sn-p 示例。问题是我想确保使用 JavaScript 在每个表单中选择一个值。
<div class="form-check form-check-inline float-right" data-application-no="1">
<input type="radio" class="form-check-input" id="shortlist" name="decisionOptions1" value="shortlist">
<label for="shortlist" class="form-check-label mr-3">Shortlist</label>
<input type="radio" class="form-check-input" id="reject" name="decisionOptions1" value="reject">
<label for="reject" class="form-check-label">Reject</label>
</div>
<div class="form-check form-check-inline float-right" data-application-no="2">
<input type="radio" class="form-check-input" id="shortlist" name="decisionOptions2" value="shortlist">
<label for="shortlist" class="form-check-label mr-3">Shortlist</label>
<input type="radio" class="form-check-input" id="reject" name="decisionOptions2" value="reject">
<label for="reject" class="form-check-label">Reject</label>
</div>
<div class="form-check form-check-inline float-right" data-application-no="3">
<input type="radio" class="form-check-input" id="shortlist" name="decisionOptions3" value="shortlist">
<label for="shortlist" class="form-check-label mr-3">Shortlist</label>
<input type="radio" class="form-check-input" id="reject" name="decisionOptions3" value="reject">
<label for="reject" class="form-check-label">Reject</label>
</div>
我真的很想知道如何去做。
现在,我正在处理这个:
function submitDecision(){
const decisionForm = document.querySelectorAll('[name^=decisionOptions]');
const shortlistSelector = document.querySelectorAll('#shortlist');
const rejectSelector = document.querySelectorAll('#reject');
for (const selector of decisionForm){
console.log(`${selector.name}: ${selector.value} , ${selector.checked}`);
if ((selector.value == "shortlist" && selector.checked == false) && (selector.value == "reject" && selector.checked == false)){
console.log("we have a problem!")
}
}
}
上面的代码显然不起作用,因为在那个 if 语句中我指的是同一个选择器。关于如何解决这个问题的任何建议。我想确保为每个申请(每个表格)选择候选名单或拒绝选项。如果没有选择,但用户尝试提交表单,我想显示一个错误。
【问题讨论】:
-
你已经接近了,必须在 vanilla js 中做吗?
-
@Ashu 不一定是这样,但我更喜欢它是在香草 JS 中
标签: javascript validation client-side-validation multiple-forms