How to mark the options on ajax return?



  • I have an array of ids and I am returning this array in the ajax response. How to compare this array with 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,
    }));
    });



  • Just one more option using jQuery, walking through the 'options' and checking whether the value of the 'option' traveled is within 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>




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2