How to handle the DOM of a XHTML file with javascript

Asked

Viewed 120 times

-2

JS file:

//Variáveis Globais - HTML
var campoMatricula = document.querySelector(".matriculaInput");
var campoNome = document.querySelector(".nomeInput");
var campoAno = document.querySelector(".anoInput");
var confirmaBtn = document.querySelector(".confirmaBtn");
var cancelaBtn = document.querySelector(".cancelaBtn");

//Funções
function validaMatricula(e){
    var tecla = String.fromCharCode(e.which);
    var regex = /[0-9]/;
    if(! (tecla.match(regex)) || campoMatricula.value.length >= 14){
        return false;
    }
}


function validaAno(e){
    var tecla = String.fromCharCode(e.which);
    var regex = /[0-9]/;
    if(! (tecla.match(regex)) || campoAno.value.length >= 4){
        return false;
    }
}

function validaNome(e) {
    var tecla = String.fromCharCode(e.which);
    var regex = /[a-zA-Z ]/;
    if(! (tecla.match(regex)) || campoNome.value.length >= 100){
        return false;
    }
}

function verificaDadosVazio(event) {
    campoNome.value = campoNome.value.trim(); // Remove espaços desnecessários
    if (campoMatricula.value == "") {
        alert("Preencha a matrícula!");
    }
    else if(campoNome.value == "" ){
        alert("Preencha o nome!");
    }
    else if(campoAno.value == ""){
        alert("Preencha o ano!");
    }
}

//Rotina Principal
campoAno.onkeypress = validaAno;
campoMatricula.onkeypress = validaMatricula;
campoNome.onkeypress = validaNome;
confirmaBtn.addEventListener("click", verificaDadosVazios);

This is my xhtml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="css/estilo_formulario.css" />
    <script type="text/javascript" src="js/formulario.js"/>

    <title>Projeto JSF</title>
</h:head>

<h:body>
    <div class="container">
        <h1 class="cabecalho">Univesidade Equipe Orbitais</h1>
        <div class="main">
            <h2 class="subtitulo">Formulário para Cadastro de Novo Aluno</h2>
            <div class="conteudoPrincipal">

                <h:link outcome="#{alunoMBean.chamaIndex()}">
                    <h:graphicImage class="imagemAcao" value="imagens/home.png" />
                </h:link>
                <p class="chamadaAcao">Página Inicial</p>

                <h:form class="formulario">
                    <h:outputLabel class="matriculaLabel" value="Matricula: "/>
                    <h:inputText class="matriculaInput" value="#{alunoMBean.aluno.matricula}"/>
                    <br/>
                    <h:outputLabel class="nomeLabel" value="Nome: "/>  
                    <h:inputText class="nomeInput" value="#{alunoMBean.aluno.pessoa.name}"/>
                    <br/>
                    <h:outputLabel class="anoLabel" value="Ano de Entrada: "/>
                    <h:inputText class="anoInput" value="#{alunoMBean.aluno.anoDeEntrada}"/>
                    <br/>
                    <h:commandButton class="confirmaBtn" value="Confirmar" action="#{alunoMBean.save}"/>
                    <h:commandButton class="cancelaBtn" value="Cancelar"/>
                </h:form>
            </div>
        </div>
    </div>

</h:body>
</html>

When I open the browser and click to display source code, I have this code:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head id="j_idt2">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="css/estilo_formulario.css" />
    <script type="text/javascript" src="js/formulario.js"></script>

    <title>Projeto JSF</title></head><body>
    <div class="container">
        <h1 class="cabecalho">Univesidade Equipe Orbitais</h1>
        <div class="main">
            <h2 class="subtitulo">Formulário para Cadastro de Novo Aluno</h2>
            <div class="conteudoPrincipal"><a href="/teste/index.xhtml"><img src="imagens/home.png" class="imagemAcao" /></a>
                <p class="chamadaAcao">Página Inicial</p>
<form id="j_idt9" name="j_idt9" method="post" action="/teste/formulario.xhtml" class="formulario" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt9" value="j_idt9" />
<label class="matriculaLabel">Matricula: </label><input type="text" name="j_idt9:j_idt11" class="matriculaInput" />
                    <br /><label class="nomeLabel">Nome: </label><input type="text" name="j_idt9:j_idt14" class="nomeInput" />
                    <br /><label class="anoLabel">Ano de Entrada: </label><input type="text" name="j_idt9:j_idt17" class="anoInput" />
                    <br /><input type="submit" name="j_idt9:j_idt19" value="Confirmar" class="confirmaBtn" /><input type="submit" name="j_idt9:j_idt20" value="Cancelar" class="cancelaBtn" /><input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="-8600842127533715592:846504525323161492" autocomplete="off" />
</form>
            </div>
        </div>
    </div></body>
</html>

Opa, I’m trying to create a javascript variable that represents a page element, the page file is xhtml, but when I enter the browser console it "converts" to html (I can’t say pq kk).

But Anyway, The problem is that javascript does not find any of these elements and they end up getting null.

NOTE: I’ve tried to put html and xhtml tags before, like this:

input.matriculaInput

and

inputText.matriculaInput

How can I make javascript to recognize tags and store them in variables?

1 answer

0


You have to assign value to these "global variables" within the functions that use them, otherwise they will always be empty, because their values are being assigned at the opening of the page and not in the functions.

For example, the variable...

var campoNome = document.querySelector(".nomeInput");

...will be empty on page loading, as the field .nomeInput nothing. By using this variable in the function validaNome, it will remain empty as you have not made any changes to the variable that has already been declared, and with that the code campoNome.value.length will always be 0.

So, within the function that will use it, you have to take the updated value of the input using another variable:

function validaNome(e) {
    var campoNomeVal = campoNome.value; // pega o valor atual do input
    var tecla = String.fromCharCode(e.which);
    var regex = /[a-zA-Z ]/;
    if(! (tecla.match(regex)) || campoNomeVal.length >= 100){
        return false;
    }
}

And the same with the other variables, one in each function where they are used.

  • Hummm, it makes a lot of sense that ae... It’s because I thought that this querySelector would return the set of the tag you know? I’ll try to do like this

  • I realized one thing, if I don’t put the global variable and declare it within the function how am I going to call the function under the onkeypress? was doing so: fieldAno.onkeypress = validationAno; but if I declare in the function will not have as

  • The button has no problem because it is not changed, but in the case of inputs yes.

  • So neither just declare the global, and call the queryselector in each function tbm, pq your n have the fields defined before calling the onkeypress it n will have how to know where I press

  • You’re right. I didn’t realize you’re using events in inputs. I changed the answer. Take a look now.

  • Man, I think I expressed myself badly in the question... the problem is not value of the variables being null, the problem is that it does not recognize the tags when it loads the page tlgd, like if I enter this file goes from the error in the browser, but if I vor on the console and type the same line of code that defines the variables it works smoothly and returns the found tag, that’s what I meant in the question, but I think it got a little confusing ksjdk

  • It must be because you are loading . js before the DOM. Try to put all the JS code inside this event: document.addEventListener("DOMContentLoaded", function(){ COLOCA TUDO AQUI DENTRO });

  • Mano, it worked !!! Tea mo!! did not know about this event man, very top

Show 3 more comments

Browser other questions tagged

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