How to select the value option returned with jQuery?

0

This variable data.uf returns me the acronym of the states. Ex ...: SC

How do I loop with jQuery to select the data-acronym corresponding to the variable data.uf ?

<select id="billing:region_id" name="billing[region_id]">
   <option value="">Por favor, selecione o estado</option>
   <option data-sigla="AC" value="485">Acre</option>
   <option data-sigla="AL" value="486">Alagoas</option>
   ...
   <option data-sigla="CE" value="490">Ceará</option>
   <option data-sigla="DF" value="511">Distrito Federal</option>
   <option data-sigla="ES" value="491">Espírito Santo</option>
    
asked by anonymous 12.04.2016 / 17:36

1 answer

4

You can do this:

$('select option').each(function() {
    $(this).attr('selected', this.dataset.sigla == dados.uf);
});

In this way, you compare the% w / o% of each% w / o% and if the value is the same as% w / o% it gives% w / o to the selected attribute.

jsFiddle: link

I saw now that you edited the question and you took dataset.sigla of the question ... so with native JavaScript you can do this:

var dados = {
    uf: 'DF'
};
var options = [].slice.call(document.querySelectorAll('option'));


function select(str) {
    options.forEach(function(option) {
        if (option.dataset.sigla == str) option.setAttribute('selected', 'selected');
        else option.removeAttribute('selected');
    });
}

select(dados.uf);

jsFiddle: link

    
12.04.2016 / 17:46