问题描述
下面是一个简单的html表单和javascript代码,用于检查字段是否为空,当用户单击提交按钮时。
Below is a code of a simple html form and javascript code for checking if the fields are empty or not, when user clicks the submit button.
问题是,即使没有填写必要的字段,表单也会被提交。
正如你所看到的,我只是一个JS编码的初学者,所以我不知道,如果问题出现在if / else语句,JS代码中的其他地方,或者表单设置不正确。
The problem is, that the form is submitted, even if the necessary fields are not filled in.As you can see, I am just a beginner with JS coding, so I don't know, if the problem is in if/else statements, somewhere else in the JS code or if the form is not set up properly.
<script>
function preveri(pov){
var preveriime = pov.ime.value;
var preverirojstvo = pov.rojstvo.value;
var preverimail = pov.email.value;
var preverikategorijo = pov.kategorija.value;
if (preveriime == "") {
document.getElementById('imeA').style.display="block";
}
if (preverirojstvo == "") {
document.getElementById('datumA').style.display="block";
}
if (preverimail == "") {
document.getElementById('emailA').style.display="block";
}
if (preverikategorijo == "") {
document.getElementById('kategorijaA').style.display="block";
}
if(preveriime != "" && preverirojstvo != "" && preverimail != "" && preverikategorijo != ""){
document.pov.submit();
}
else{
return false;
}
}
</script>
<h4>OBRAZEC ZA SPLETNE PRIJAVE</h4>
<br/>
<form name="pov" method="POST" action="thankUPage.php">
<input name="ime" type="text" placeholder="Ime in Priimek"></input>
<input name="rojstvo" type="text" placeholder="Datum rojstva"></input>
<input name="email" type="text" placeholder="E-pošta"></input>
<input name="kategorija" type="text" placeholder="Kategorija"></input>
<textarea name="povprasaj" placeholder="Povprašaj"></textarea>
<input type="submit" name="submit" id="submit" value="Pošlji!" onclick="preveri(pov)" />
</form>
<div id="imeA" class="imeA">Obvezno polje!</div>
<div id="datumA" class="datumA">Obvezno polje!</div>
<div id="emailA" class="emailA">Obvezno polje!</div>
<div id="kategorijaA" class="kategorijaA">Obvezno polje!</div>
</div>
提前Tnx!
Tnx in advance!
推荐答案
你在click事件上返回false。您需要将您的回调函数绑定到表单的提交事件,因此返回false将取消表单的提交。
You're returning false on the click event. You need to bind your callback function to the form's submit event, so returning false will cancel the form's submission.
在表单字段中按enter将提交表单并且可能不会触发提交按钮上的点击事件。
Pressing "enter" while in a form field will submit the form and might not trigger the click event on the submit button.
<form name="pov" method="POST" action="thankUPage.php" onsubmit="return preveri(this);" >
这篇关于即使验证失败,表单也会提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!