How to add an array to a value attribute?

0

Hello! I'm having trouble using a multiple select field with a choseen-select plugin in a form link

<form id="cadastro" action="process_teste.php" method="post">
<select id="form-edit-selecionar" name="fornecedor[]" data-placeholder="Fabricantes" style="width:330px;" multiple class="chosen-select" tabindex="2">
<?php while($row2Fnc = mysqli_fetch_assoc($result2Fnc)) :?>
        <option value="<?=$row2Fnc["id"];?>"><?=$row2Fnc["blablabla"];?></option>
<?php endwhile ?>
      </select>
 <button type="submit">Enviar</button>

$.getJSON('process_forn.php?valor='+data, function (dados){ 
        var options_val = [];   
            for (var i = 0; i < dados.length; i++) {
            options_val += dados[i].id;
            }           
            $("#form-edit-selecionar").val(options_val);
            alert(options_val)  
    });
    
asked by anonymous 12.09.2014 / 15:01

1 answer

1

So I understand you want a popular select with options. Correct me if I'm wrong ...

To populate the array:

$.getJSON('process_forn.php?valor='+data, function (dados){ 
    var options_val = [];   
        for (var i = 0; i < dados.length; i++) {
            options_val[i] = dados[i].id;
        }           
});

To call the first option (within the for):

alert(options_val[0]);

To fill your select with the options (within the for):

$("#form-edit-selecionar").append("<option value=" + options_val[i] + "> Nome da opção <option>");

As you use a plugin, you may have to refresh your select so that the plugin remounts with the new data. Usually with the js you've enabled it at the beginning of the page load it works, but if it does not work check out the plugin's documentation if there is another way.

    
12.09.2014 / 20:27