How to mark options in ajax return?

Asked

Viewed 101 times

0

I have an array of ids and I’m returning this array in the ajax response. How to compare this array with the select options and mark the option if it matches the array index?

In PHP, we use the function in_array()

var options = data.options;
var checkeds = data.checkeds;

$.each(options, function(i, item){
    $('#ajax_locals').append($('<option>', {
        value: i,
        text : item,
    }));
});

2 answers

1


Just one more option using jQuery, traversing the 'options' and checking whether the value of the 'option' traversed is inside the array:

var arr = ["valor1","valor2",'valor5'];

$('select').find('option').each(function (i) {
   var $this = $(this);
   var $val = $this.val();
   if($.inArray($val, arr) !== -1){
    $this.prop('selected',true);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple='true'>
  <option value="valor1">Valor1</option>
  <option value="valor2">valor2</option>
  <option value="valor3">valor3</option>
  <option value="valor4">valor4</option>
  <option value="valor5">valor5</option>
</select>

0

You can go through the options and mark what exists on array:

let array = [4, 5, 3, 7];

$("option").each((idx, item) => {
  
  array.indexOf(Number(item.value)) > -1 ? item.selected = true : item.selected = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Browser other questions tagged

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