1
I am with a problem, that I can no longer solve, I am trying to fill the fields from an option that is contained within a select
which is filled automatically with the foreach
, but it’s not working
<script language="JavaScript">
// Tratando o objeto de manipulacao DOM
const select = document.getElementById("cliente");
const state = document.getElementById("estado");
// Trata o evento change do select
select.addEventListener("change", function(event)
{
// Obtem o option que foi selecionado
let _selectedOption = this.options[this.selectedIndex];
// Obtem o valor da propriedade data-state
let _state = _selectedOption.getAttribute("data-state");
// Atualiza o valor do campo estado
state.value = _state;
});
</script>
<form action="" method="post" class="form-horizontal">
<!-- Cliente -->
<div class="col-lg-7">
<!-- Legenda -->
<label for="clientes" class="label label-primary">Cliente</label>
<!-- Campo -->
<select name="cliente" id="cliente" class="form-control">
<?php
foreach ($clientes as $cliente)
{
?>
<!-- Opcoes -->
<option value="<?= $cliente['id'] ?>" data-state="<?= $cliente['estado'] ?>"> <?= $cliente['nome'] ?> </option>
<?php
}
?>
</select>
</div>
<!-- Data do pedido -->
<div class="col-lg-4">
<!-- Legenda -->
<label for="dataPedido" class="label label-primary">Data do Pedido</label>
<!-- Legenda -->
<input type="text" name="dataPedido" id="dataPedido" class="form-control text-center" readonly="" value="<?= date("d/M/Y")?>">
</div>
<!-- Estado -->
<div class="col-lg-7">
<!-- Legenda -->
<label for="estado" class="label label-primary">Estado</label>
<!-- Campo -->
<input type="text" name="estado" id="estado" class="form-control text-center" readonly="">
</div>
</form>
I want when I select an option from select
, the state field and other fields that will come in the future, be filled with the respective values. The property data-state
store the state and in the future new properties will be created to store the values of the next fields.
And what is currently happening when you select a client? An error appears on the console?
– Woss
it appears two messages: Typeerror: select is null[Learn More] and The getPreventDefault() method should no longer be used. Instead, use defaultPrevented.
– Rodrigo Prado
Rodrigo: you have this
script
on the page as it is in the question? In that case you have to put it after HTML, for Javascript to find HTML.– Sergio
This I did not know, I thought the script in front would work the same way, now it worked. Thanks
– Rodrigo Prado