John John - 1 month ago 12
jQuery Question

Auto Select From Dropdown If Only Two Options

I got 2 select dropdowns that sometimes have only 2 options each

The "Please Select" and the "True Option".



if ($('.product-options .inputbox').size() == 2) {
$('.product-options .inputbox').not(.val('')).attr('selected', true);
}

<div class="product-options">
<div id="option-98" class="options_class">
<div>
<strong>Size:</strong>
<select id="options98" class="inputbox" name="options[98]" onchange="updatePrice();">
<option value="" selected="selected">--- Please Select ---</option>
<option value="99">Small</option>
</select>
</div>
</div>
<div id="option-99" class="options_class">
<div>
<strong>Color:</strong>
<select id="options99" class="inputbox" name="options[99]" onchange="updatePrice();">
<option value="" selected="selected">--- Please Select ---</option>
<option value="100">Black</option>
</select>
</div>
</div>
</div>




Answer

You can use .each function to loop through selects.

$(function(){
  $("select").each(function(i, e){
    var $e = $(e);
    
    if($e.children().length == 2){
      $e.find("option[value='']").attr("selected", false);
      $e.find("option[value!='']").attr("selected", true);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-options">
<div id="option-98" class="options_class">
    <div>
        <strong>Size:</strong>
        <select id="options98" class="inputbox" name="options[98]" onchange="updatePrice();">
            <option value="" selected="selected">--- Please Select ---</option>
            <option value="99">Small</option>
        </select>
    </div>
</div>
<div id="option-99" class="options_class">
    <div>
        <strong>Color:</strong>
        <select id="options99" class="inputbox" name="options[99]" onchange="updatePrice();">
            <option value="" selected="selected">--- Please Select ---</option>
            <option value="100">Black</option>
        </select>
    </div>
</div>
<div id="option-100" class="options_class">
    <div>
        <strong>Select with 3 values:</strong>
        <select id="options100" class="inputbox" name="options[100]" onchange="updatePrice();">
            <option value="" selected="selected">--- Please Select ---</option>
            <option value="100">One</option>
            <option value="101">Two</option>
        </select>
    </div>
</div>
</div>