Search code examples
javascripthtmljqueryvalidationdisable-link

Hide/locking a <form> button until form is completely filled with validation


I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:

<form action="action_page.php" method="GET">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"<br><br>
  <label for="lname">Last name:</label>
  <input type="text" id="lname" name="lname"<br><br>
</form>

All I need now is validation and how to lock or hide the button.

I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:

You have not finished the information input for the survey. Please input "Your First Name" and "Your Last Name" to enter the survey.



When they finish, I will input a loading icon until fully loaded.


Code Language(s)

I use fiddles to make my code, so I use:

  • HTML
  • JSON
  • Pinch of jQuery (loading icon)

Answer Expectations


In my answers, I need:

  • Recommended Code Language
  • Code for note purposes
  • Crossed out attributes
  • Attributes before coding explanations

EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.


Solution

  • Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)

    <form action="action_page.php" method="get" >
      <label for="fname">First name:</label>
      <input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
      <label for="lname">Last name:</label>
      <input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
      <button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
    </form>
    
    <script>
      var fname_var = document.getElementById("fname");
      var lname_var = document.getElementById("lname");
    
      var submit_btn_var = document.getElementById("submit_btn");
    
      function inputEntries(){
        if(lname_var.value != "" && fname_var.value != "")
            submit_btn_var.disabled = false;
        else
          submit_btn_var.disabled = true;
      }
    </script>
    

    What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!