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.

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>

Fiddle Demo


Post a Comment for "Datalist Option Validation Required"