1. Home
  2. Third-Party Integration
  3. jQuery
  4. How to use jQuery to Show/Hide a Form on Click

How to use jQuery to Show/Hide a Form on Click

You can use jQuery to show or hide a form on click. The easiest way to do this is to use the toggle effect.

See the Pen How to Use jQuery to Show/Hide Form on Click by pair Networks (@pairdocs) on CodePen.

This is an interactive code display that shows you the HTML, CSS, jQuery, and a demo of the output.

Setting Up HTML for Toggle

The first step is to create an HTML form and button.

<button type="button" id="formButton">Toggle Form!</button>

<form id="form1">
  <b>First Name:</b> <input type="text" name="firstName">
  <b>Last Name: </b><input type="text" name="lastName">
   <button type="button" id="submit">Submit</button>
</form>

The form and button should have distinguishing classes or IDs that gives jQuery the ability to call it out specifically. In the example above, the button that will toggle the form has an ID of “formButton” and the form has an ID of “form1.”

Setting Up CSS for Toggle

In the CSS, make sure you set the form to:

display:none;

This will make sure the form is not visible until the button is first clicked. In our example, it would be:

#form1 {

display:none;

}

Setting up jQuery for Toggle

In the jQuery, you need to set up the button to toggle the form to show and hide. See the example below:

$("#formButton").click(function(){
        $("#form1").toggle();
    });

In the example, the ID of the button, “formButton,” is called and when it is clicked, it toggles the form. The form is called by its ID “form1.” When the button is clicked, the form’s visibility will toggle to display or hide.

Updated on April 27, 2018

Was this article helpful?

Related Articles