我目前有一个包含以下代码的表单,问题是当用户按下表单提交按钮时,即使没有选中必填字段,onclick
调用仍然会被触发,我怎么能使您必须在获得触发器之前完成必填字段?
<form method="post">
<div class="form-group">
<select id="inputState" class="form-control" style="width: 100%">
<option>10,000 credits</option>
<option>25,000 credits</option>
<option>50,000 credits</option>
<option>75,000 credits</option>
<option>100,000 credits</option>
</select>
</div>
<div class="text-center">
<div class="row justify-content-center mb-2">
<div class="col-12 col-md-8 text-center">
<p class="mb-0 small text-muted"><strong>Promotion Disclaimer</strong>
<br>You will be required to install a free mobile app from our sponsors to receive your Coins for free. This process only takes a minute or two and you can remove the app once you're finished.</p>
</div>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="defaultCheck1" required>
<label class="form-check-label" for="defaultCheck1">
I agree to Promotion Disclaimer
</label>
</div>
<br>
<button class="btn btn-primary btn-sm btn-continue" data-step="3" onclick="call_locker();">Continue</button>
</div>
</form>
最佳答案
使用表单 onsubmit
事件,将您的 call_locker 调用移动到 form
元素中。当有 submit
事件时调用。您可以在单击按钮时默认触发所述事件。要阻止页面刷新,您可以添加 event.preventDefault()
或从该函数返回 false。这里我有一个 call_locker
的模拟函数,它返回 false。
<script>
call_locker = () => { console.log('called locker'); return false; }
</script>
<form method="post" onsubmit="return call_locker();">
<div class="form-group">
<select id="inputState" class="form-control" style="width: 100%">
<option>10,000 credits</option>
<option>25,000 credits</option>
<option>50,000 credits</option>
<option>75,000 credits</option>
<option>100,000 credits</option>
</select>
</div>
<div class="text-center">
<div class="row justify-content-center mb-2">
<div class="col-12 col-md-8 text-center">
<p class="mb-0 small text-muted"><strong>Promotion Disclaimer</strong>
<br>You will be required to install a free mobile app from our sponsors to receive your Coins for free. This process only takes a minute or two and you can remove the app once you're finished.</p>
</div>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="defaultCheck1" required>
<label class="form-check-label" for="defaultCheck1">
I agree to Promotion Disclaimer
</label>
</div>
<br>
<button class="btn btn-primary btn-sm btn-continue" data-step="3">Continue</button>
</div>
</form>
关于javascript - 带有必填字段的 Onclick 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56249344/