PHP – Multiselect require field if option is selected [closed]

You could use Javascript which allows the validation on the front end and doesn’t require a page load, something like the following should work for you:

<head>
<script type="text/javascript">
function SelectValidator() {
  // Get the select object
  var index = document.getElementById("geographic").selectedIndex;
  var select = document.getElementById("geographic").options;

  // Get our input elements
  var county = document.getElementById('county');
  var state = document.getElementById('state');
  var zipcode = document.getElementById('zipcode');

  if (select[index].value === "county") {
    if (county.value === null || county.value === "") {
      alert("Please complete the County field");
    } else {
      alert("You could simply put a return statement here.");
    }
  } else if (select[index].value === "state") {
    if (state.value === null || state.value === "") {
      alert("Please complete the state field");
    } else {
      alert("You could simply put a return statement here.");
    }
  } else if (select[index].value === "zip") {
    if (zipcode.value === null || zipcode.value === "") {
      alert("Please complete the Zip Code field");
    } else {
      alert("You could simply put a return statement here.");
    }
  }
}
</script>
</head>

And your form:

<form>
<select multiple="multiple" name="geographic" id="geographic">
    <option value="state">State</option>
    <option value="county">County</option>
    <option value="zip">Zip Code</option>
</select>

<label for="state">What state?</label>
<input id="state" name="state" type="text">

<label for="county">What County?</label>
<input id="county" name="county" type="text">

<label for="zipcode">What is the Zip Code? *</label>
<input id="zipcode" name="zipcode" type="text">


<button type="button" onclick="SelectValidator()">Display index</button>
</form>

Leave a Comment