1

I do have a form with a variable amount of dropdowns I want to check, if something is selected before submit.

What I have is this javascript, but it works for the 1st dropdown only.

var ddl = document.getElementById("status");
  var selectedValue = ddl.options[ddl.selectedIndex].value;
     if (selectedValue == "")
    {
     alert("Machine status must be selected");
     return false;
    }

for this dropdown (this comes from a loop so I have a variable amount of them within the form)

<select name="mstatus[]" id="status">
  <option value="">please select</option>
  <option value="status1">ok</option>
  <option value="status2">not ok</option>
</select>

Any hint in the right direction, much appreciated. thanks

Oliver
  • 156
  • 1
  • 13
  • 1
    `getElementById()` only returns the first match of the ID. Also, in the HTML standard, it is assumed every ID is unique to one element only. Try using `getElementsByClassName()` and tagging your `select` elements with a class. https://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class – Aman Singh Sep 08 '18 at 07:21

1 Answers1

0

I would suggest giving the selects you wish to iterate through the same class and use Jquerys .each(). https://api.jquery.com/each/

For the validation I would use a data tag to help you with the alert label

<select class="form-select" data-label="Machine status"></select> 

Then the JS code

$('.form-select').each(function(index, element) {
    let value = $(element).val();
    let label = $(element).data("label");
     if (value === "") {
        alert(`${label} status must be selected`);
        return false;
    }
});

Without Jquery you could do.

document.querySelectorAll('.form-select').forEach(function (element, index) {
//do same code here
});
Noel Kriegler
  • 509
  • 3
  • 11