Complete fields with select

Asked

Viewed 188 times

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?

  • it appears two messages: Typeerror: select is null[Learn More] and The getPreventDefault() method should no longer be used. Instead, use defaultPrevented.

  • 1

    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.

  • This I did not know, I thought the script in front would work the same way, now it worked. Thanks

1 answer

1


The problem:

When Javascript is run it will search for the pieces of HTML it needs, but once the Browser processes the page into pieces as it gets received from the server it does not expect to have the whole content.

This means that when Javascript is read everything that comes after in the code text is not yet known by the Browser.

So at the time of parse of the Javascript code the HTML does not yet exist in the eyes of the Browser and const select = document.getElementById("cliente"); will give null.

Solution:

Place this script at the end of the HTML, before closing the tag </body>.

Alternatively, tell Javascript to only run the code when the page load is complete:

window.onload = function(){
    // 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;
    });
}

Browser other questions tagged

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