How do I mark options in ajax return?

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 index of the array?

In PHP, we use the in_array ()

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

$.each(options, function(i, item){
    $('#ajax_locals').append($('<option>', {
        value: i,
        text : item,
    }));
});
    
asked by anonymous 30.11.2017 / 18:32

2 answers

1

Just one more option using jQuery, traversing the 'options' and checking if the value of 'option' traveled 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><selectmultiple='true'><optionvalue="valor1">Valor1</option>
  <option value="valor2">valor2</option>
  <option value="valor3">valor3</option>
  <option value="valor4">valor4</option>
  <option value="valor5">valor5</option>
</select>
    
30.11.2017 / 18:54
0

You can scroll through the options and mark what exists in 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><optionvalue="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
    
30.11.2017 / 18:44