When the user selects a combobox element, it is an activity that occurs on the client side (ie the browser), and the code that runs on the server, PHP, does not and can not be sure when happens.
So we need code that runs on the client, that is, javascript , which will address this subject. Let's say the code that creates the combobox and the textbox are below:
$query = "SELECT nome FROM Medicos";
$data = mysqli_query($dbconn, $query);
$result = mysqli_num_rows($data);
?>
<form name="medicos" method="post" action="administrador_medicos_populate.php">
<label for="cbMedicos">Selecione um Medico</label>
<select id="cbMedicos">
<option>Selecione...</option>
<?php while($prod = $data->fetch_assoc()) {
echo '<option value="'.$prod['nome'].'">'.$prod['nome'].'</option>';
}
?>
</select>
<input type="text" id="txtMedico" value="" />
We need to continue with a code that takes the value of combobox cbMedicos
and puts it in the txtMedico
text box when it changes. For that, we need a tag <script>
.
Ordinarily, I would say to put the tags <script>
within the tag <head>
, but then we would need to listen for a second event to wait for the page to be created before tying the event in cbMedicos
; then put the following code on your page somewhere then where you set cbMedicos
:
<script type="text/javascript">
document.getElementById("cbMedicos").addEventListener("change", function () {
document.getElementById("txtMedico").value = this.value;
});
</script>
This code gets a reference to the combobox through its id using getElementById()
, and adds an event using addEventListener()
" for the change
event. When the value of the combobox changes, it will execute this function which is the second parameter of addEventListener()
.
Within the function, the this
pointer points to the combobox itself, so we get a reference to the text box using the same document.getElementById()
and assign the value of the combobox (property .value
) to its value. p>
Adapt the code here to your situation and see if it works.
To bring various information:
If you want to bring multiple information from multiple doctors, there are many options, but it is probably best to serialize your information to JSON using json_serialize()
and assign it to a javascript variable, which the onchange
event of the combobox will use to popular all other controls:
<html lang="pt-pt">
<head>
</head>
<body>
<?php
$servername = "localhost";
$username = "isabelso_isabel";
$password = "password";
$dbname = "isabelso_db";
$dbconn = mysqli_connect($servername, $username, $password, $dbname)or die("Failed to connect to database:" . mysqli_error($dbconn));
// vamos dar um alias para cada coluna conforme o nome do
$query = "SELECT nome as txtNome, email as txtEmail /*, etc. */ FROM Medicos";
$data = mysqli_query($dbconn, $query);
$result = mysqli_num_rows($data);
$meujson = array();
?>
<form name="medicos" method="post" action="">
<label for="cbMedicos">Selecione um Medico</label>
<select id="cbMedicos">
<option>Selecione...</option>
<?php while($prod = $data->fetch_assoc()) {
echo '<option value="'.$prod['txtNome'].'">'.$prod['txtNome'].'</option>';
$meujson[$prod['txtNome']] = $prod; // coleciona as linhas no $meujson
}
?>
</select>
<label for="txtNome">Nome:</label>
<input type="text" id="txtNome" value="" />
<label for="txtNome">Email:</label>
<input type="text" id="txtEmail" value="" />
<!-- etc. -->
</form>
<script type="text/javascript">
// Armazenar a coleção de dados (chaveada por nome) numa variável javascript
var dados = <?php echo json_encode($meujson); ?>;
document.getElementById("cbMedicos").addEventListener("change", function ()
{
// obtém a linha referente ao médico selecionado
var linha = dados[this.value];
// a forma "for (<variável> in <objeto>) itera sobre as chaves
// (nomes de propriedades) do objeto mencionado,
// e põe cada uma na variável de índice por vez
for (var ch in linha) {
(document.getElementById(ch) || {}).value = linha[ch];
}
});
</script>
That is, I am creating in PHP a array()
that I will use as a dictionary to collect all the information of all doctors, keyed by the name of the professional (could be by id of the table, in this case we would have to bring it too of the bank).
After that, in <script>
, we create a variable that will store all this information. To do this, we write the information we collect as JSON (javascript object notation), which is conveniently the syntax for creating object literals in javascript. Thus, dados
is a variable that contains all the information we will need to fill out for each doctor - just be careful that there are no doctors or too much information, otherwise the page will be heavy. If you stay, we'll have to change strategy and bring information asynchronously using AJAX, probably.
Finally, in the change
event of the combobox, we get the element of the dados
object that corresponds to the selected doctor (remember that $meujson
and therefore dados
is a dictionary whose keys are the names of doctors) and we iterate about the keys of this document, that on purpose are the IDs of the controls that must be filled by them, marking each one in turn.
Two details:
-
First, the for (
variable in
object )
iterates over the keys , not the values of object . So you still have to dereference the object to get the value corresponding to the key (using the index operator []
, just like PHP arrays).
For example, if you have an object obj = { a: 1, b: 2 };
and you say for (var i in obj) { alert(i); }
, two popups will appear, one saying "a" and the other "b". To get "1" and "2", we would have to say for (var i in obj) { alert(obj[i]); }
.
-
Second, the (
object || {})
gameplay is a similar trick to or die()
of PHP: if document.getElementById(ch)
fails, because there is no control with an ID equal to key in question, it returns a value null
; if we tried to assign something to the value
property of null
we would make an error and the script would stop. However, since null
is false, we apply a or
operator (which in javascript is written ||
) and an empty {}
object.
So, if a control with a given id does not exist, document.getElementById(ch)
returns null
, but (document.getElementById(ch) || {})
returns {}
, which is an empty object, and property will be assigned to it and then it goes be discarded and collected by the garbage collector, without making a mistake.