Very good days.
I am having difficulties to fill some "input" fields depending on what is selected in a select field.
I think it should be in Ajax, because I want the RUT, Telephone, Address and eMAil fields to be updated depending on what is selected in the Select Company.
Now, i’ḿ trying with php. I am using PDO and MVC.
In my model I have:
public function TraerEmpresas()
{
try
{
$result = array();
$stm = $this->pdo->prepare("SELECT * FROM empresas");
$stm->execute();
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
In my view, i have:
<div class="col-md-4 mt-3">
<div class="form-floating">
<label for="floatingName">Empresa</label>
<select name="empresa" id="empresa" class="form-select" style="height:80px;" placeholder="Empresa">
<option value = ""></option>
<?php
foreach($this->model->TraerEmpresas() as $r):
?>
<option value="<?php echo $r->razonsocial; ?>"><?php echo $r->razonsocial; ?></option>
<?php
endforeach;
?>
</select>
</div>
</div>
<div class="col-md-4 mt-3">
<div class="form-floating">
<input type="text" name="rut_dest" value="<?php echo $r->rut; ?>" class="form-control" placeholder="RUT" required>
<label for="floatingName">RUT</label>
</div>
</div>
<div class="col-md-4 mt-3">
<div class="form-floating">
<input type="text" name="tel_emp_dest" value="<?php echo $r->telefono; ?>" class="form-control" placeholder="Teléfono" required>
<label for="floatingName">Teléfono</label>
</div>
</div>
<div class="col-md-8 mt-3">
<div class="form-floating">
<input type="text" name="direccion_dest" value="<?php echo $r->direccion; ?>" class="form-control" placeholder="Dirección" required>
<label for="floatingName">Dirección</label>
</div>
</div>
<div class="col-md-6 mt-3">
<div class="form-floating">
<input type="text" name="mail_emp_dest" value="<?php echo $r->email; ?>" class="form-control" placeholder="eMail" required>
<label for="floatingName">eMail</label>
</div>
</div>
Is not working.
Can someone give me a hand?
What is expected is that: by selecting an option from a select field, other attached fields update their content.
2
Answers
I managed to get it working as follows:
and the script:
Thanks to all!
Following your clarification in the comments, I believe this is what you are trying to get:
First, you need to add an
onChange()
prompt to your<select>
element. (The function itself is seen below)Second, you need to add and id to all your text elements.
You should remove all the echoes in the text elements. They don’t work anyways – PHP only loads data once, when the page is loaded. Any dynamic changes to the page later can only be achieved with JS.
NOTE: this function MUST be in a script tag at the end of your page (after
</body>
), because it uses data you pull on the<select>
line.