How to add an array to a value attribute?

Asked

Viewed 449 times

0

Hello! I’m having problems I’m using in a form a multiple select field with the choseen-select plugin http://harvesthq.github.io/chosen/

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

and I’m getting data from php via ajax with $getJSON and want to add the id in the value of select, I tried it here but it didn’t work, the variable options_val has all ids, but select this null!

$.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)  
    });

1 answer

1

From what I understand you want to popular a select with options. Correct me if I’m wrong...

To popular 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 (inside the for):

alert(options_val[0]);

To fill your select with the options (inside 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 give a "refresh" in your select so that the plugin will go back with the new data. Usually with the js you enabled it at the beginning of page loading works, but if it doesn’t work see in the plugin documentation if there is another way.

Browser other questions tagged

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