Fill multiple select with data stored in the bank

0

Good afternoon everyone.

I need guidance from you regarding select multiple.

I have the select below:

<select class="form-control" id="dias_semana" multiple name="diasDaSemana[]" required>
<option value="">Selecione...</option>
<option value="Domingo">Domingo</option>
<option value="Segunda">Segunda-Feira</option>
<option value="Terca">Terça-Feira</option>
<option value="Quarta">Quarta-Feira</option>
<option value="Quinta">Quinta-Feira</option>
<option value="Sexta">Sexta-Feira</option>
<option value="Sabado">Sábado</option>
</select>

Through the above select I am able to select more than one option and send it to the bank.

My difficulty is to display the data that is in the database.

I was trying to do this:

$("#dias_semana").val(diasDaSemana[]);

But it did not work. How can I do this?

    
asked by anonymous 03.10.2016 / 18:58

2 answers

1

See this code:

var diasDaSemana = ["Segunda", "Quarta", "Quinta"];//Deverá ser carregada do banco de dados

$.each(diasDaSemana, function(idx, val) {
  $('#dias_semana option[value=' + val + ']').attr('selected', true);
});

The variable diasDaSemana should be loaded from the database, then each will select each option.

    
03.10.2016 / 20:51
0

A simple plugin for jQuery:

(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    this.empty();
    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
        .text(option.text);
      self.append($option);
    });
  };
})(jQuery, window);

Use it this way:

$("#foo").replaceOptions(options);

Source: link

    
03.10.2016 / 20:55