Home > Software engineering >  How to hide form button if two input fields have the same sentences
How to hide form button if two input fields have the same sentences

Time:11-27

I have an HTML form that disable submit button if both fields have the same for, but I want it the submit button to be hidden instead, please how can I do that?

<form id="my-form" action="" method="post">

<input type="text" id="inp-1" value="">

<input type="text" id="inp-2" value="">

<button type="submit">Signup project</button>

</form>

<script>
/** select the form and both the inputs, select them once and use them as many as needed */
const myForm = document.getElementById('my-form'),
  inp1 = document.getElementById('inp-1'),
  inp2 = document.getElementById('inp-2');

/** 
* listen for "submit" events on the form 
* if the trimmed values of both the inputs is the same then we prevent the form from being submitted
*/
myForm.addEventListener('submit', e => inp1.value.trim() === inp2.value.trim() && e.preventDefault());
</script>

CodePudding user response:

This will solve the problem.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form id="my-form" action="" method="post">
      <input type="text" id="inp-1" value="" />
      <input type="text" id="inp-2" value="" />
      <button type="submit" id="submit">Signup project</button>
    </form>
  </body>
  <script>
    const myForm = document.getElementById("my-form"),
      inp1 = document.getElementById("inp-1"),
      inp2 = document.getElementById("inp-2");
    submitBtn = document.getElementById("submit");
    inp1.addEventListener("input", (e) => {
      const val = e.target.value;
      if (val.length > 1 && inp2.value.length > 1) {
        if (val == inp2.value) {
          submitBtn.style.display = "none";
        } else {
          submitBtn.style.display = "inline";
        }
      }
    });
    inp2.addEventListener("input", (e) => {
      const val = e.target.value;
      if (val.length > 1 && inp1.value.length > 1) {
        if (val == inp1.value) {
          submitBtn.style.display = "none";
        } else {
          submitBtn.style.display = "inline";
        }
      }
    });
    // myForm.addEventListener(
    //   "submit",
    //   (e) => inp1.value.trim() === inp2.value.trim() && e.preventDefault()
    // );
  </script>
</html>

Hope it helped.

  • Related