How to select the value option returned with jQuery?

Asked

Viewed 166 times

0

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

How I make a loop with jQuery to select the date-symbol correlately to the variable Uf data.?

<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>
  • I saw now that you edited the question and took jQuery from the question, added more to the answer.

1 answer

4


You can do it like this:

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

So you compare the dataset.sigla of each option and if the value is the same as dados.uf he gives true attribute.

jsFiddle: https://jsfiddle.net/ucbn55ot/


I just saw that you edited the question and you took it jQuery question... then with native Javascript you can do so:

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: https://jsfiddle.net/ucbn55ot/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.