我目前有一个包含以下代码的表单,问题是当用户按下表单提交按钮时,即使不检查必填字段,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>
答案 0 :(得分:3)
使用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>
答案 1 :(得分:2)
有一个解决您问题的简单方法。
您可以使用onclick
事件来代替使用onsubmit
事件,除非提交表单,否则该事件不会调用该函数。
如果未填写具有required
属性的元素,浏览器将不会提交表单,因此,如果您使用onsubmit
事件,则直到required
才会调用该函数。字段已填写。
onclick="call_locker();"
应该成为onsubmit="call_locker();"
答案 2 :(得分:0)
还有另一种解决问题的方法。 如果您希望这样做,以使浏览器不会在每次单击“提交”按钮且字段不满足时刷新自身(并因此提交表单),则可以使您的javascript代码通过防止使用默认的提交键(每次按下时刷新浏览器)
。JavaScript示例
call_locker(event)
{
if (document.getElementById().value === undefined &&
document.getElementById(defaultCheck1).value === undefined)
{
event.preventDefault();
}
}