How to select Option value with Ajax data return?

Asked

Viewed 156 times

1

I have the following HTML code:

<select id="priorities-info" class="form-control selectpicker" data-live-search="true" disabled="" tabindex="-98">
    <option value="1" data-tokens="Alta">Alta</option>
    <option value="2" data-tokens="Média">Média</option>
    <option value="3" data-tokens="Baixa">Baixa</option>
</select>

I’m trying to compare the data-tokens this way:

$('#priorities-info').each(function() {
    $(this).attr('selected', this.dataset.tokens == responseData.Type);
});

But I’m not getting it, does anyone have any idea?

  • What is the value of responseData.Type?

  • @Marconi Type: Média

1 answer

2


In the selector I believe you should include options and check if the attribute value data-tokens is the same as returned by ajax:

$('#priorities-info option').each(function() {
  if ( $(this).attr('data-tokens') == 'Média')
    $(this).prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="priorities-info" class="form-control selectpicker" data-live-search="true" tabindex="-98">
    <option value="1" data-tokens="Alta">Alta</option>
    <option value="2" data-tokens="Média">Média</option>
    <option value="3" data-tokens="Baixa">Baixa</option>
</select>

  • Thank you Lucas, just an observation if someone is using the Bootstrap Select equal to me, I advise to put $('#priorities-info').selectpicker('refresh'); after the if

  • Wonder @Wagnerviana!

Browser other questions tagged

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