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.

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.

jQuery is an open-source software permissive under an MIT license. jQuery is not a product of Pair Networks, Inc., and Pair Networks provides no warranty for jQuery. Please note that there are many levels of javascript libraries available. Please consult with your IT professional for advice and guidance on an appropriate library. This specific product may or may not meet your needs. Pair Networks, Inc. is providing support for this tutorial for your convenience and is not responsible for jQuery's performance. Please read carefully the terms and scope of services for any online service or product you are considering purchasing or using.

Updated on February 26, 2020

Was this article helpful?

Related Articles

Need Support?
Can't find the answer you're looking for?
Contact Support