Reputation: 41
I want to click button then set select with option 501
. However, it only works on the first click. The second click then it goes to the first option. Does any one know about this issue?
function test() {
jQuery('.state_autocomplete option').removeAttr('selected');
jQuery('.state_autocomplete').attr('value', 'Pernambuco');
jQuery('.state_autocomplete option').each(function() {
if (jQuery(this).val() == 501) {
jQuery(this).attr('selected', 'selected');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="billing:region_id" name="billing[region_id]" title="Estado" class="form-control validate-select state_autocomplete required-entry" style="" defaultvalue="" value="Pernambuco">
<option value="">Selecione...</option>
<option value="496">Minas Gerais</option>
<option value="499">Paraná</option>
<option value="498">Paraíba</option>
<option value="497">Pará</option>
<option value="500" >Pernambuco</option>
<option value="501">Piauí</option>
</select>
<button onclick="test()" value='b'>aaa</button>
Upvotes: 1
Views: 39
Reputation: 337560
Your logic is a lot more complicated than it needs to be. Simply use the setter of val()
to change the selected option. You should also remove the inline onclick
handler on the button. Use an unobtrusive event handler instead. Something like this:
$('#set').click(function() {
$('.state_autocomplete').val('501');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="billing:region_id" name="billing[region_id]" title="Estado" class="form-control validate-select state_autocomplete required-entry" style="" defaultvalue="" value="Pernambuco">
<option value="">Selecione...</option>
<option value="496">Minas Gerais</option>
<option value="499">Paraná</option>
<option value="498">Paraíba</option>
<option value="497">Pará</option>
<option value="500" >Pernambuco</option>
<option value="501">Piauí</option>
</select>
<button id="set" value='b'>aaa</button>
Upvotes: 3