Stacker Stacker - 6 months ago 13
Javascript Question

How can I check if any dropdown in a class is empty?

I have multiple date of birth dropdowns (day, month, year). How can I have a div show if any of them are null?

I've tried something like this

if ($(".MyClass").val() === "") {
$("#showDiv1").show();
}else{
$("#showDiv1").hide();
}


with a div like

<div id="showDiv1">
My Div
</div>

<select class="MyClass">
<option value="">Choose Value..</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

<select class="MyClass">
<option value="">Choose Value..</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>


This only seems to work if it's just one select, rather than multiple selects.

Thanks,
k

fiddle: https://jsfiddle.net/62a1pdsk/

Answer

Try this

$("select").change(function() {
  var flag = 0;
  $("select").each(function(a, b) {
    if ($(this).val() == "") {
      flag = 1;
    }
    flag == 1 ? $("#showDiv1").show() : $("#showDiv1").hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showDiv1">
  This div is display if any dropdown value is ""
</div>

<select>
  <option value="">Choose Value..</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

<select>
  <option value="">Choose Value..</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
  <option value="D">D</option>
</select>