Fill select Multiple with data stored in the database

Asked

Viewed 752 times

0

Good afternoon to all.

I need some 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 to the bank.

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

I was trying to do this:

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

But it didn’t work.How can I do this?

  • Could you clarify what is the diasDaSemana[]? In javascript this means nothing unless it is a variable and the [] at the end will cause an error. I might think that your goal would be to select the last item of the array diasDaSemana, or even catch the element with name=daysDaSemana. Could clarify, so I can help you better.

  • @Filipeteixeira is a variable yes.... also can not explain, because I took this from the net and worked to save in the bank... the problem is to take the bank and show the user what was saved... for example.... select Sunday... there on my edit screen... this select option Sunday, would have to be marked. Here I am strolling

2 answers

1


Look at 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 shall be loaded from the database, subsequently the each will select each option.

  • followed his example and it didn’t work: https://jsfiddle.net/4yydLL5L/

  • solved. http://jsfiddle.net/McddQ/1/ thanks for the explanation.

  • I am happy. Thank you for choosing my answer. : D

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);

It’s used this way:

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

Source: https://stackoverflow.com/a/16654226/5660495

  • From what I understand, the user did not ask how to replace the options with the values of an Array, but rather select in select the values that came from the database

Browser other questions tagged

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