Return false does not work Typescript

Asked

Viewed 96 times

-1

I am making a code with Typescript and I check if a field has less than 9 digits, if it has less than 9, should not proceed to Ubmit, but for some reason it is proceeding.

<form method="post">
  Nome: <input type="text" id="nome"/>
  <button type="submit" id="enter">Submit</button>
</form>

My typescript code looks like this:

document.getElementById("enter").addEventListener("click", function () {
  if ((<HTMLInputElement>document.getElementById("nome")).value.length < 9) {
    (<HTMLInputElement>document.getElementById("tet")).innerHTML = "O Campo \"Nome\" deve conter 9 dígitos.";

    setTimeout(function () {
      (<HTMLInputElement>document.getElementById("tet")).innerHTML = "";
    }, 5000);

    return false;
  }
});

and is inside a

window.onload = function () {}

and right after him, still inside the onload has a

(<HTMLInputElement>document.getElementById("form")).addEventListener("submit", function () {
});

still inside the window.onload.

What am I doing wrong?

  • Just for the sake of consciousness: you have an element with the id tet on screen, right?

  • I have yes kkk @LINQ

1 answer

0


What happens there is that the form submission is being triggered the moment you click the button.

To prevent this, it is possible to use the method preventDefault() and then fire the Submit manually.

Note that if there are other forms on the page you need to specify which form should be submitted.

Take an example:

document.getElementById("enter").addEventListener("click", function (e) { 
    e.preventDefault(); // Previne que o submit seja disparado

    const nomeEl = document.getElementById("nome");
    
    if (nomeEl.value.length >= 9) {
        document.querySelector('form').submit(); // Faz o submit
    }
    else {        
        console.log("O Campo \"Nome\" deve conter 9 dígitos.");
    }
});
<form method="post">
  Nome: <input type="text" id="nome"/>
  <button type="submit" id="enter">Submit</button>
</form>

  • I think it would be good to note also that a cast is being done in tet for HTMLInputElement, and soon after the innerHTML of that input is changed. But inputs do not have internal HTML, it is quite possible that @Samuel is casting all elements to HTMLInputElement, which is not only unnecessary, but also makes the code error-prone.

  • So dude, this code helps me a little bit. What happens is that I don’t just do Ubmit, on (<HTMLInputElement>document.getElementById("form")).addEventListener("submit", function () {&#xA;}); i perform other actions.

  • What about it? Just adding preventDefault avoids automatic Submit.

  • Okay, I’ve managed to figure it out through your example. Thank you @LINQ

Browser other questions tagged

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