我有一个表单和一个脚本,可以在字段留空时弹出一个对话框。问题是,它只有在两个字段都留空时才有效。我正在尝试弄清楚如何让它在其中一个字段留空时以及是否正常工作。
脚本
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
if(sendMsg.mile.value=='' || isNaN(sendMsg.mile.value))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(sendMsg.location.value=='' || isNaN(sendMsg.location.value))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
表单
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
最佳答案
现在修复它,添加输入模式以确保只有数字以及标签上的要求。同样,我无法在答案中格式化代码,所以我添加了另一个,因为我整晚都在这里
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n in Numbers only\n";
}
if(location=='')
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="text" pattern="[0-9]+" class="form-control" data-validation-required-message="Please enter your Google Mileage" required id="mile" name="mile"/>
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" required placeholder="BUSINESS NAME" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
关于javascript - 我的 javascript 需要什么条件?它是一个脚本,弹出一个对话框,其中包含字段留空的表单验证备注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007147/