HTML template in Java

Asked

Viewed 59 times

0

I’m having a problem assigning a role to a input

I have 2 HTML templates in Java

var forgotPassword = ' <form action="#">'+
                            '<fieldset>'+
                                '<legend class="title"><span class="lang" key = "SendmePassword">Send me password</span></legend>'+
                                    '<div class="input_block">'+
                                        '<div class="input_wrap">'+
                                            '<input type="text" id="sing_email" class="input" placeholder="Email">'+
                                            '<label for="sing_email" class="label_mail"></label>'+
                                        '</div>'+
                                        '<p>Enter a valid e-mail, the password will be sent to you  </p>'+
                                    '</div>'+
                                '<input type="submit" value="Sing IN" class="btn btn_red" id="backtoSingIN">'+
                                '<input type="submit" value="Send" class="btnSend btn_red" id="send">'+
                            '</fieldset>'+
                        '</form>';

//======================
var singIN = '<form action="#">'+
                '<fieldset>'+
                    '<legend class="title"><span class="lang" key = "LogIn">SING IN</span></legend>'+
                    '<div class="input_block">'+
                        '<div class="input_wrap">'+
                            '<input type="text" id="mail" class="input" placeholder="Email">'+
                            '<label for="mail" class="label_mail"></label>'+

                        '</div>'+
                        '<div class="input_wrap">'+
                            '<input type="text" id="pass" class="input" placeholder="Password">'+
                            '<label for="pass" class="label_pass"></label>'+
                        '</div>'+
                    '</div>'+
                    '<a href="#" class="forgotPass" id="forgot"><span class="lang" key ="ForgotPassword">Forgot password</span>?</a>'+
                    '<input type="submit" value="Sing IN" class="btn btn_red">'+
                '</fieldset>'+
            '</form>';
//================================================================================================================================================
function loadSingIN(){
    return singIN;
}


function loadForgotPassword(){
    return forgotPassword;
}

I can use both models that way

//LOAD FORGOT PASSWORD
document.getElementById("forgot").addEventListener('click', function(){
    console.log("fui clicado");
    document.getElementById("root").innerHTML = loadForgotPassword();
});


    document.getElementById("send").addEventListener('click', function(){
    console.log("fui clicado");
    document.getElementById("root").innerHTML = loadSingIN();
    });

but when I try to assign a click function to my input with id "send"

it returns me an error on the console

Error:Uncaught Typeerror: Cannot read Property 'addeventlistener' of null

I tried using $(ducument). ready but I couldn’t solve it, someone could help me ?

  • This error is displayed as there is no input with id "send" when Javascript is executed. Where part of your HTML code is mounted?

1 answer

2


This is because you are adding an event there is an element that has not yet been attached to the document tree (DOM) and therefore "doesn’t exist yet".

The following "minimum example" reproduces the same error:

let model = `<h1 id="header">Hello World</h1>`


document.getElementById('header').addEventListenner('click', console.log, true)

Apparently you are working with the idea of showing and hiding two dynamic forms, alternating between both.

A more concise approach would be to show one form by default and hide it and show the other and vice versa ... the following "minimal example" shows this:

// link para recuperação
let forgot = document.getElementById("forgot")
// link para login
let signin = document.getElementById('backtoSingIN')
// formulário de login
let formSignin = document.getElementById('signin-form')
// formulário de recuperação
let formForgot = document.getElementById('forgot-form')

// evento no link para recuperação
forgot.addEventListener('click', function(evt) {
    // esconder este formulário
    formSignin.classList.add('hide')
    // mostrar o outro formulário
    formForgot.classList.remove('hide')
}, true)

// evento no link para login
signin.addEventListener('click', function(evt) {
    // esconder este formulário
    formForgot.classList.add('hide')
    // mostrar o outro formulário
    formSignin.classList.remove('hide')
}, true)
.hide {
    display: none!important;
}
<!-- formulário padrão -->
<form id="signin-form" action="#">
    <fieldset>
        <legend class="title"><span class="lang" key = "LogIn">SING IN</span></legend>
        <div class="input_block">
            <div class="input_wrap">
                <input type="text" id="mail" class="input" placeholder="Email">
                <label for="mail" class="label_mail"></label>
            </div>
            <div class="input_wrap">
                <input type="text" id="pass" class="input" placeholder="Password">
                <label for="pass" class="label_pass"></label>
            </div>
        </div>
        <a href="#" class="forgotPass" id="forgot"><span class="lang" key ="ForgotPassword">Forgot password</span>?</a>
        <input type="submit" value="Sing IN" class="btn btn_red">
    </fieldset>
</form>

<!-- formulário "escondido" -->
<form id="forgot-form" class="hide" action="#">
    <fieldset>
        <legend class="title"><span class="lang" key = "SendmePassword">Send me password</span></legend>
            <div class="input_block">
                <div class="input_wrap">
                    <input type="text" id="sing_email" class="input" placeholder="Email">
                    <label for="sing_email" class="label_mail"></label>
                </div>
                <p>Enter a valid e-mail, the password will be sent to you  </p>
            </div>
        <button type="button" class="btn btn_red" id="backtoSingIN">Sing IN</button>
        <input type="submit" value="Send" class="btnSend btn_red" id="send">
    </fieldset>
</form>

In its original example the action of "back" this conditioned there is a <input type="submit"> ... I took the liberty of modifying to a button element <button> because the recovery form already has a submit.

Basically use CSS and a class to hide and add and remove this class between forms.

I used the property .classList to add and remove the form class, legacy browsers (such as IE 9 and earlier) may need a "polyfill" or use jQuery for such.

If for some reason you cannot render your forms by default and can only add them dynamically, call your event listeners after adding them to the document and preferably add both with this logic: one visible (the pattern) and one hidden.

The following example expresses this:

let ModelSignin = `
<!-- formulário padrão -->
<form id="signin-form" action="#">
    <fieldset>
        <legend class="title"><span class="lang" key = "LogIn">SING IN</span></legend>
        <div class="input_block">
            <div class="input_wrap">
                <input type="text" id="mail" class="input" placeholder="Email">
                <label for="mail" class="label_mail"></label>
            </div>
            <div class="input_wrap">
                <input type="text" id="pass" class="input" placeholder="Password">
                <label for="pass" class="label_pass"></label>
            </div>
        </div>
        <a href="#" class="forgotPass" id="forgot"><span class="lang" key ="ForgotPassword">Forgot password</span>?</a>
        <input type="submit" value="Sing IN" class="btn btn_red">
    </fieldset>
</form>`

let ModelForgot = `
<!-- formulário "escondido" -->
<form id="forgot-form" class="hide" action="#">
    <fieldset>
        <legend class="title"><span class="lang" key = "SendmePassword">Send me password</span></legend>
            <div class="input_block">
                <div class="input_wrap">
                    <input type="text" id="sing_email" class="input" placeholder="Email">
                    <label for="sing_email" class="label_mail"></label>
                </div>
                <p>Enter a valid e-mail, the password will be sent to you  </p>
            </div>
        <button type="button" class="btn btn_red" id="backtoSingIN">Sing IN</button>
        <input type="submit" value="Send" class="btnSend btn_red" id="send">
    </fieldset>
</form>`

// renderize os formulários e após chame seus ouvintes
function RenderForms() {
    // adicione os formulários ha um elemento
    document.body.insertAdjacentHTML('afterbegin', ModelSignin + ModelForgot)

    // trate os eventos em seus formulários

    let forgot = document.getElementById("forgot")
    let signin = document.getElementById('backtoSingIN')
    let formSignin = document.getElementById('signin-form')
    let formForgot = document.getElementById('forgot-form')

    // evento no link para recuperação
    forgot.addEventListener('click', function(evt) {
        // esconder este formulário
        formSignin.classList.add('hide')
        // mostrar o outro formulário
        formForgot.classList.remove('hide')
    }, true)

    // evento no link para login
    signin.addEventListener('click', function(evt) {
        // esconder este formulário
        formForgot.classList.add('hide')
        // mostrar o outro formulário
        formSignin.classList.remove('hide')
    }, true)
}

// chame a função de renderização quando quiser
RenderForms()
.hide{
  display:none!important;
}

In the above example I used document.body as element (container) to add both forms and method .insertAdjacentHTML(), you can use any element of your choice as "container".


References:

https://developer.mozilla.org/en-US/docs/Web/API/Element/addEventListener

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

.classList polyfill: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Polyfill

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

  • Thank you so much for the help, and for the details in the explanation :)

Browser other questions tagged

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