Skip to content Skip to sidebar Skip to footer

Datalist Option Validation Required

Here is all the details

Solution 1:

Make array of all the option values and test the value of input with it.

  • The Array.from() method creates a new Array instance from an array-like or iterable object.
  • The Array#map() method creates a new array with the results of calling a provided function on every element in this array.
  • The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

functionvalidate() {
  var fromVal = document.myForm.From.value;
  var toVal = document.myForm.To.value;
  varfrom = 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.!");
    returnfalse;
  } elseif (optionValuesArrFrom.indexOf(fromVal) === -1) {
    alert("item not in from list.!");
    returnfalse;
  } elseif (toVal == "") {
    alert("Please select To Place.!");
    returnfalse;
  } elseif (optionValuesArrTo.indexOf(toVal) === -1) {
    alert("item not in to list.!");
    returnfalse;
  }
}
<formaction="order.php"method="post"name="myForm"onsubmit="return(validate());"><inputtype="text"list="From"name="From"autocomplete="off"placeholder="From Place"><datalistid="From"><optionvalue="Bankura Bus Stand"></option><optionvalue="Bankura Hospital"></option><optionvalue="Katjuridanga"></option><optionvalue="Lokepur"></option></datalist><inputtype="text"list="To"name="To"autocomplete="off"placeholder="To Place"><datalistid="To"><optionvalue="Bankura Bus Stand"><optionvalue="Bankura Hospital"><optionvalue="Katjuridanga"><optionvalue="Lokepur"></datalist><inputtype="submit"value="Book Now"></form>

Fiddle Demo

Post a Comment for "Datalist Option Validation Required"