Reputation: 9
Here is all the details
<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 Validation
<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>
Everything work fine, but i want only option value otherwise show alert error: when click on submit button
<input type="submit" value="Book Now">
I want it by same script procedure... Thanks in advance
Upvotes: 0
Views: 2250
Reputation: 36599
Make array
of all the option values and test the value of input with it.
Array.from()
method creates a new Array instance from an array-like
or iterable
object.Array#map()
method creates a new array
with the results of calling a provided
function on every element in this array
.indexOf()
method returns the first index at which a given element can be found in the array, or -1
if it is not present.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;
}
}
<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>
Upvotes: 1