How to insert an imput into a combobox (CB) value via Javascript

Asked

Viewed 23 times

1

I have a list of clients in a Mysql database and I am pulling, via PHP, this data for a combobox and I want the user to click on a client name inside the combobox some inputs to be filled with this value, right after clicking on an "add" button. But the value being returned is the "id" of the CB and not the client’s name and surname.

Follow my form:

<form method="post" action="classes/consulta.php">
    <div class="row">
    <div class="col-6">
        <div class="form-group">
            <label>Nome</label>
            <input type="text" id="nome_input" class="form-control" name="nome">
        </div>
        </div>
        </div>
        <div class="row">
        <div class="col-6">
        <div class="form-group">
            <label>Sobrenome</label>
            <input type="text" class="form-control" name="sobrenome">
        </div>
        <button type="submit" class="btn btn-primary">Adicionar</button>
        </div>
        </div>
    </form>

Follow my CB:

    <label>Nome do Cliente:</label>
    <select name="ativo" id="nome_CB">
        <?php while($reg = $resposta->fetch_array()) { ?>
        <option  value="<?php echo $reg["cod_cli"]?>"> <?php echo $reg["nome_cli"]." ".$reg["sobrenome_cli"]?> </option>

        <?php }?>
    </select>
    <button onclick="alimentarCampo()" class="btn btn-primary">Adicionar</button>

Follow my JS:

function alimentarCampo() {
var minhaLista = document.getElementById("nome_CB");
document.getElementById("nome_input").value = minhaLista.options[minhaLista.selectedIndex].value;
}

1 answer

1


Is that the value of the option selected is the client code. You need to grab the option text using textContent instead of value:

function alimentarCampo() {
   var minhaLista = document.getElementById("nome_CB");
   document.getElementById("nome_input").value = minhaLista.options[minhaLista.selectedIndex].textContent;
}
<select name="ativo" id="nome_CB">
     <option  value="1">Maria José</option>
     <option  value="2">Fulano Detal</option>
 </select>
 <button onclick="alimentarCampo()" class="btn btn-primary">Adicionar</button>
 <input type="text" id="nome_input" class="form-control" name="nome">

  • Is it possible to separate the name and the surname, which is within the same line of the select, so that each one goes to a different imput? Ex: "So-and-so" on an imput and "Detal" on another imput.

Browser other questions tagged

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