user3329007 user3329007 - 2 months ago 8
Javascript Question

make an option selected when input attribute equals 0

I have this html select below:

<select name="options[35]" id="select_35" class=" required-entry product-custom-option" title="" onchange="opConfig.reloadPrice()">
<option value="">Selecione...</option>
<option value="99" price="0">5ml </option>
<option value="98" price="50">50ml +R$50,00</option>
<option value="97" price="90">100ml +R$90,00</option>
</select>


Note that the
id
and
name
attribute are dynamic.

I would like to have a solution using javascript, that in the load of my site, it will check what price="" attribute equals to 0, and add "selected" in this
specific option

I don't have knowledge enough to solve this,so ask for help.

Tks.

Answer

So select the option with a property selector and set the property selected.

$(function(){
    $('option[price="0"]').prop("selected",true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select name="options[35]" id="select_35" class=" required-entry product-custom-option" title="" onchange="opConfig.reloadPrice()">
  <option value="">Selecione...</option>
  <option value="99" price="0">5ml </option>
  <option value="98" price="50">50ml +R$50,00</option>
  <option value="97" price="90">100ml +R$90,00</option>
</select>