Javascript PHP and HTML, onload usage

Asked

Viewed 63 times

-2

Come on, guys, I wonder if the onload logic is right in this case. I need this script to run when loading the page. What would be the best way to implement ?

HTML and Javascript and PHP

 <div class="col-xs-3">
        <span>Matrícula</span>            
        <input  type="number" onload="verificaMatriculaExists(this)" value="<?php echo $dados[0]->matricula ?>">                                                        
 </div>

The problem with adding directly would be that you would have to add all of this code inside the view which would make the POO meaningless

It turns out that this onload will bring all this data through this implementation

Javascript

//Verificar se matrícula já existe na base de dados.

function verificaMatriculaExists(elemento) {

    var matricula = (elemento.name === 'matricula' ? document.querySelector('#dados-matricula-1') : document.querySelector('#dados-matricula-2'));



    var matriculaValue = elemento.value;

    $.post("<?= base_url('pedidos/verificaMatricula/'); ?>", {
        matricula: matriculaValue
    }, function(get_retorno) {



        if (get_retorno == '0') {



            alert('Matrícula não existente no sistema, cadastre um cliente antes de prosseguir');

            limpaDadosCliente(matricula);

            document.getElementById('cad_cliente').type = 'button';

            document.getElementById('div_cad_cliente').hidden = false;

            matricula.hidden = true;



        } else {





            matricula.hidden = false;



            var json = JSON.parse(get_retorno);

            var cliente = json.cliente;

            var cadastro = json.cadastro;

            var pessoa = json.pessoa;

            var endereco = json.endereco;



            //console.log(get_retorno);

            matricula.querySelector('#numero-matricula').innerHTML = `Dados Matrícula ${cliente.matricula}`;
            //nome-cliente.querySelector('#nome-matricula').innetHTML = `Dados Matrícula ${cliente.matricula}`;
            



            //Bancos

            json.bancos.forEach((banco) => {

                matricula.querySelector('#dados-bancarios-matricula').innerHTML += `

                              <p id='teste'>

                                <span class='banco'>${banco.nome_banco}</span>

                                <span class='agencia'>${banco.agencia}</span>

                                <span class='conta'>${banco.conta}</span>

                              </p>`;

            });



            //Contatos

            json.contatos.forEach((contato) => {

                matricula.querySelector('#contato-matricula').innerHTML += `

                              <p id='teste'>

                               <span class='nome'>${contato.nome_cont}</span>

                                <span class='fone'>${contato.telefone_cont}</span>

                                <span class='fone'>${contato.celular_cont}</span>

                                <span class='email'>${contato.email_cont}</span>

                              </p>`;

            });



            //Anexos

            json.anexos.forEach((anexo) => {

                matricula.querySelector('#anexo-matricula').innerHTML += `

                              <p id='teste'>

                                 <span class='tipo'>${anexo.tipo_arquivo}</span>

                                 <span class='arquivo'>${anexo.nome_arquivo}</span>

                              </p>`;

            });



            //Atendimentos

            json.atendimentos.forEach((atendimento) => {

                matricula.querySelector('#atendimento-matricula').innerHTML += `

                              <p id='teste'>

                                <span class='data'>${atendimento.data_ocorrencia} ${atendimento.hora_ocorrencia} </span>

                                <span class='dado'>${atendimento.ocorrencia}</span>

                              </p>`;

            });



            //Históricos

            json.historicos.forEach((historico) => {

                matricula.querySelector('#historico-matricula').innerHTML += `

                              <p id='teste'>

                               <span class='data'>${historico.data_historico} ${historico.hora_historico} </span>

                                <span class='dado'>${historico.ocorrencia_historico}</span>

                                <span class='userDado'>${historico.admin}</span>

                              </p>`;

            });



            preencherDadosCliente(matricula, pessoa, cliente, endereco);

       

        }
    capturar = document.getElementById("nome-matricula").value;
    document.getElementById("nome-cliente").value = capturar;

    });

}



function limpaDadosCliente(matricula)

{

    matricula.querySelector('#numero-matricula').innerHTML = '';

    matricula.querySelector('#nome-matricula').value = ""

    matricula.querySelector('#apelido-matricula').value = "";

    matricula.querySelector('#cpf-matricula').value = "";

    matricula.querySelector('#rg-matricula').value = "";

    matricula.querySelector('#emissor-matricula').value = "";

    matricula.querySelector('#sexo-matricula').value = "";

    matricula.querySelector('#dt-nascimento-matricula').value = "";

    matricula.querySelector('#telefone-matricula').value = "";

    matricula.querySelector('#celular-matricula').value = "";

    matricula.querySelector('#email-matricula').value = "";

    matricula.querySelector('#profissao-matricula').value = "";

    matricula.querySelector('#cep-matricula').value = "";

    matricula.querySelector('#endereco-matricula').value = "";

    matricula.querySelector('#numero-matricula').value = "";

    matricula.querySelector('#complemento-matricula').value = "";

    matricula.querySelector('#bairro-matricula').value = "";

    matricula.querySelector('#estado-matricula').value = "";

    matricula.querySelector('#cidade-matricula').value = "";

    matricula.querySelector('#dados-bancarios-matricula').innerHTML = "";

    matricula.querySelector('#contato-matricula').innerHTML = "";

    matricula.querySelector('#anexo-matricula').innerHTML = "";

    matricula.querySelector('#atendimento-matricula').innerHTML = "";

    matricula.querySelector('#historico-matricula').innerHTML = "";



}



function preencherDadosCliente(matricula, pessoa, cliente, endereco)

{

    matricula.querySelector('#nome-matricula').value = (typeof pessoa.nome === 'undefined' ? '' : pessoa.nome);

    matricula.querySelector('#apelido-matricula').value = (typeof pessoa.apelido === 'undefined' ? '' : pessoa.apelido);

    matricula.querySelector('#cpf-matricula').value = (typeof pessoa.cpf === 'undefined' ? '' : pessoa.cpf);

    matricula.querySelector('#rg-matricula').value = (typeof pessoa.rg === 'undefined' ? '' : pessoa.rg);

    matricula.querySelector('#emissor-matricula').value = (typeof pessoa.emissor === 'undefined' ? '' : pessoa.emissor);

    matricula.querySelector('#sexo-matricula').value = (typeof pessoa.sexo === 'undefined' ? '' : (pessoa.sexo === '1' ? 'Masculino' : 'Feminino'));

    matricula.querySelector('#dt-nascimento-matricula').value = (typeof pessoa.data_nascimento === 'undefined' ? '' : pessoa.data_nascimento);

    matricula.querySelector('#telefone-matricula').value = (typeof cliente.telefone === 'undefined' ? '' : cliente.telefone);

    matricula.querySelector('#celular-matricula').value = (typeof cliente.celular === 'undefined' ? '' : cliente.celular);

    matricula.querySelector('#email-matricula').value = (typeof cliente.email === 'undefined' ? '' : cliente.email);

    matricula.querySelector('#profissao-matricula').value = (typeof cliente.profissao === 'undefined' ? '' : cliente.profissao);

    matricula.querySelector('#cep-matricula').value = (typeof endereco.cep === 'undefined' ? '' : endereco.cep);

    matricula.querySelector('#endereco-matricula').value = (typeof endereco.nome_endereco === 'undefined' ? '' : endereco.nome_endereco);

    matricula.querySelector('#numero-matricula').value = (typeof endereco.numero === 'undefined' ? '' : endereco.numero);

    matricula.querySelector('#complemento-matricula').value = (typeof endereco.complemento === 'undefined' ? '' : endereco.complemento);

    matricula.querySelector('#bairro-matricula').value = (typeof endereco.bairro === 'undefined' ? '' : endereco.bairro);

    matricula.querySelector('#estado-matricula').value = (typeof endereco.id_estado === 'undefined' ? '' : endereco.id_estado);

    matricula.querySelector('#cidade-matricula').value = (typeof endereco.id_cidade === 'undefined' ? '' : endereco.id_cidade);







}
  • That way it won’t happen

  • Tendeu, what is the correct way to implement @Leocaracciolo? I happen to be bringing a fetch after this onload that will come with some data, but for that I need the onload that will load automatically to view the data

  • should put the event in the "body" tag, not an input...

  • Here’s the question the element I want to take to do the procedure is in the input and not in the body, could explain better @Ricardopunctual

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

  • @Leocaracciolo successfully marked ! Thank you

Show 1 more comment

1 answer

0


Let’s assume that <?php echo $dados[0]->matricula ?> return number 12

function verificaMatriculaExists() {
   //valor do campo com id = qqId
   var campo = document.getElementById('qqId').value;
   console.log(campo);
}
window.onload = verificaMatriculaExists();
 
<input id="qqId" type="number" value=12> 
                                                           

may also at @Ricardo Pontual’s suggestion

function verificaMatriculaExists() {
   //valor do campo com id = qqId
   var campo = document.getElementById('qqId').value;
   console.log(campo);
}
<body onload="verificaMatriculaExists()">

<input id="qqId" type="number" value=12> 

would work for a body with several inputs ? yes

function verificaMatriculaExists() {
var z = document.getElementById("qqId").value;
var z2 = document.getElementById("qqId2").value;
var z3 = document.getElementById("qqId3").value;
  var x = document.getElementsByClassName("example");
  x[0].innerHTML = z;
  x[1].innerHTML = z2;
  x[2].innerHTML = z3;
}
<body onload="verificaMatriculaExists()">
<input id="qqId" type="number" value=12> 
<input id="qqId2" type="number" value=10000> 
<input id="qqId3" type="number" value=40> 
 
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>

  • Excellent answer, I had already thought about this way to be able to implement, I thought there were other ways to solve these problems, I don’t want to copy the input, but thank you for the answer. It was very well structured.

  • The reason I don’t use this way of copying and pasting is because I already use this check functionMatriculaExists in other parts of the system and for engineering and software architecture reasons I would need to create a exactly equal function including the copy of the element as it was explained in the reply. This is out of the question and would require more code

  • As explained by @Leocaracciolo Ricardo Pontual commented would serve only an input inside the body or work for a body with several inputs ?

  • @developerGo, if it goes straight in the can is not good?

  • Give a look at the size of the code you would have to add @Leocaracciolo just edited the question

  • @developerGo, I saw

  • What do you suggest I do in this case ? @Leo Caracciolo

  • @should loperGo work for a body with multiple inputs ? yes

Show 3 more comments

Browser other questions tagged

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