以下是所有细节
<form action="order.php" method="post" name="myForm" onsubmit="return(validate());">
<input type="text" list="From" name="From" autocomplete="off" placeholder="From Place">
<datalist id="From">
<option value="Bankura Bus Stand">
<option value="Bankura Hospital">
<option value="Katjuridanga">
<option value="Lokepur">
</datalist>
<datalist id="To">
<option value="Bankura Bus Stand">
<option value="Bankura Hospital">
<option value="Katjuridanga">
<option value="Lokepur">
</datalist>
Javascript验证
<script>
function validate() {
if (document.myForm.From.value == "") {
alert("Please select From Place.!");
return false;
if (document.myForm.To.value == "") {
alert("Please select From Place.!");
return false;
</script>
一切正常,但我只想要选项值,否则显示警告错误:点击提交按钮
<input type="submit" value="Book Now">
我想通过相同的脚本程序...提前致谢
答案 0 :(得分:1)
使所有选项值array
并使用它测试输入值。
Array.from()
method从array-like
或iterable创建一个新的Array实例
对象。 Array#map()
方法创建一个new array
,其结果是调用提供的结果
对此array
。 indexOf()
方法返回可在数组中找到给定元素的第一个索引,如果不存在则返回-1
。
function validate() {
var fromVal = document.myForm.From.value;
var toVal = document.myForm.To.value;
var from = document.getElementById('From');
var to = document.getElementById('To');
var optionValuesArrFrom = Array.from(from.options).map(function(elem) {
return elem.value;
});
var optionValuesArrTo = Array.from(to.options).map(function(elem) {
return elem.value;
});
if (fromVal == "") {
alert("Please select From Place.!");
return false;
} else if (optionValuesArrFrom.indexOf(fromVal) === -1) {
alert("item not in from list.!");
return false;
} else if (toVal == "") {
alert("Please select To Place.!");
return false;
} else if (optionValuesArrTo.indexOf(toVal) === -1) {
alert("item not in to list.!");
return false;
}
}
&#13;
<form action="order.php" method="post" name="myForm" onsubmit="return(validate());">
<input type="text" list="From" name="From" autocomplete="off" placeholder="From Place">
<datalist id="From">
<option value="Bankura Bus Stand"></option>
<option value="Bankura Hospital"></option>
<option value="Katjuridanga"></option>
<option value="Lokepur"></option>
</datalist>
<input type="text" list="To" name="To" autocomplete="off" placeholder="To Place">
<datalist id="To">
<option value="Bankura Bus Stand">
<option value="Bankura Hospital">
<option value="Katjuridanga">
<option value="Lokepur">
</datalist>
<input type="submit" value="Book Now">
</form>
&#13;