Keep selected option loaded dynamically

2

I need to keep the option chosen in the combobox after the page is submitted, I have a function that does this, but only for combobox static, for the dynamic combobox it does not work. I'm already searching for hours and can not find anything.

function cursos() {

  $.getJSON('https://localhost/uan/curso/pesquisaPor/', {}).done(function(data) {
    $.each(data, function(id, valor) {

      $("#curso").append('<option value="' + valor.id + '">' + valor.nome + '</option>');
    });
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="control-group">
  <label class="control-label">Curso<span class="required">*</span>
  </label>
  <div class="controls">
    <select class="span6 m-wrap" id="curso" name="curso">
      <option value="">Selecciona um curso</option>
    </select>


  </div>
</div>

The courses function returns all courses that are in the database and populates the select dynamically, it happens that whenever I submit the form I wanted it to mark up the selected option ..

    
asked by anonymous 03.08.2015 / 01:15

3 answers

2

I think an easy way to resolve this is by sending the value of select to the page you need.

Suppose you receive select as follows:

$_POST["lista"];

You can send this variable to the page you want, via POST or via GET .

When you are generating <option> , you need to check for $_POST["lista"] , if so, use it to option on select .

Example:

<?php
$lista = array(
  "um" => 1,
  "dois" => 2,
  "tres" => 3,
  "quatro" => 4
);

// Aqui você verifica se a variável $_POST["lista"]
// e não é nula
$selecionado = "tres";
?>

<select name="opcoes">

<?php
foreach($lista as $chave => $valor) {
    if($selecionado == $chave) {
      echo "<option value=".$chave." selected>".$valor."</option>";
    } else {
      echo "<option value=".$chave.">".$valor."</option>";
    }
}
?>
</select>
    
03.08.2015 / 01:50
1

Joins another JSON property that returns from the server. In addition to id and nome you could join selected , as Boolean.

Then in JavaScript it would look like:

$.each(data, function(id, valor) {
      var selected = valor.selected ? 'selected="selected"' : '';
      $("#curso").append('<option ' + selected + ' value="' + valor.id + '">' + valor.nome + '</option>');
});
    
03.08.2015 / 10:51
0

Pass a parameter through the URL. And retrieve via get and check in JavaScript if there is any select option equal to the value retrieved by get.

    
03.08.2015 / 15:47