Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type.

My objective is to display an appropriate form based on the selected value of the user. While I have expertise in PHP for functionality, I lack experience in jQuery. I am seeking guidance on how to execute this task without the need to reload the page. Can someone provide instructions on implementation or suggest an alternative method?

Answer №1

To implement a category dropdown list, follow the steps below:

HTML Code

Dropdown Menu

<select id="category">
   <option value="#form1">Category 1</option>
   <option value="#form2">Category 2</option>
   <option value="#form3">Category 3</option>
</select>

Forms Section

<form id="form1">
</form>    

<form id="form2">
</form>

<form id="form3">
</form>

jQuery Script

$(function(){
    var forms = $('form'); // Cache all form elements
    forms.hide(); // Hide forms initially

    $('#category').on('change', function(){
        forms.hide();                // On change, hide all forms
        var formId = $(this).val();  // Get the selected form id to show
        $(formId).show();    // Find and display the form based on its id in cached forms.
    });

});

Answer №2

To make elements appear or disappear on a webpage, you can utilize jQuery's show() and hide() methods:

For instance:

$('#element1').hide();
$('#element2').show();

In this demonstration, the elements are structured like this:

<div id="element1">...</div>
<div id="element2">...</div>
<div id="element3">...</div>

If you wish to add some visual effects, consider using fadeIn() and fadeOut() from jQuery.

Answer №3

One way to make elements appear and disappear on a webpage is by using the jQuery toggle() function:

$('#this_element').toggle();

You can learn more about this function in the documentation here.

When you use toggle(), the selected elements will either be shown or hidden immediately without any animation, simply by changing the display property of the CSS. If the element was originally visible, it will become hidden; if it was hidden, it will become visible. The display property is stored and restored as needed. If an element's display value is inline and it goes from hidden to visible, it will once again be displayed inline.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to Generating a Dynamic HTML Menu

Is "dynamically" the correct term for what I'm trying to achieve? * I am looking to have a basic one-level menu appear on every one of the 80 pages on my website. The menu items will be updated regularly - some added, some removed, and so on. What is ...

The enigma of HTML forms never ceases to baffle

Currently, I am enrolled in a Vue.js course and have recently delved into the topic of forms and their management. The concept posed about how the < select > tag operates has left me puzzled. Is it correct to assume that its value corresponds to the ...

Drop the <span> element into a paragraph by utilizing JQuery's drag and drop feature

Trying to drag and drop <span> into <p>. The code is functional, but encountering 3 issues: When editing content inside <p> by typing (e.g. three words) and then dragging <span> into <p>, the newly typed words are consider ...

Tips on utilizing the useState hook for storing numerous key objects?

Currently, I am working with a candlestick chart for a cryptocurrency that displays data over different timeframes such as 1 minute and 30 minutes. Below is the code snippet that sets the initial state to show a 1-hour chart when a user first visits: const ...

Issue encountered while retrieving information using Axios in a Vue.js application

Currently, I am in the process of developing a full stack application using Vue.js and Fastify.js (a Node framework). The Vue app is supposed to retrieve data from the API I created and display it in the browser console. However, I am encountering an issue ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Retrieve the value of the element and combine them together (The parseFloat function may not work as expected

The following code is what I am currently working with: var num1=$("#num1").val(); //the num1 value is 12.60 //html code for this number <input id="num1" value="12.60" /> num1=parseFloat(num1).toFixed(2); var num2=$("#num2").text(); //the num2 valu ...

Creating a responsive layout with two nested div elements inside a parent div, all styled

I'm currently facing an issue with using padding in my CSS to make the two divs inside a parent div responsive at 50% each. However, when combined, they exceed 100%. I suspect this is due to the padding, but I'm unsure how to resolve it. .column ...

Ways to update a value in a table by comparing two JSON objects

I am currently working with two JSON files containing data as shown below: JSON 1: let classes = [{ "Class": "A", "as_of": "12/31/2020", "student": [{ "raji": { "eng": ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Oops! Vue.js router configuration is throwing an error because it's unable to read properties of undefined when trying to access 'use'

Description: I have been working on a leaderboard web application using Vue.js. When I tried to launch the server on localhost after finishing my code, I encountered an error. The error message I received is as follows: Uncaught runtime errors: ERROR Cann ...

Concerns with the Width of Gutters in Susy

I am working with a 24 Susy column grid and trying to create boxes that span 6 columns each, allowing for 4 boxes per row. However, I also want to add gutters around them within a wider container that is 24 columns wide. Despite my efforts, the columns do ...

Differences in wrapping between IE11 and Chrome/Firefox: <DIV>

Take a look at this jsfiddle link using IE 11, Chrome, and FireFox. Here is the HTML code I am working with: <div style="width:120px;background-color:#EE1111;"> <div class="daytext"><b>27</b></div> <div class="dayitem"> ...

Is it possible to repeat this action by swiping to the left?

I'm currently developing an app in PhoneGap and retrieving information using JSON. My goal is to trigger this function again with Ajax when I slide left. This is the code I have so far. Thank you to everyone for your assistance. $(document).ready( ...

Adjust the size of col-lg-3

Is there a way to adjust the size of my col-lg based on different screen resolutions? I'm looking for a solution that can change the size of col-lg depending on the screen resolution. For example: .col-lg-3 { /* styles for screens with 1366x768p ...

Managing responses from ajax requests that can handle both text and json formats

After submitting a form via Ajax and receiving a response from the servlet in either text or JSON format, I'm wondering if there is a way to handle both types of responses. I've read through the jQuery/Ajax documentation, but the JQuery Ajax page ...

"Trouble arises when a single quote is passed from the controller to the client-side MVC

In the Controller method, Serverside code is stored in ViewData with values like 'Double-Click to edit', '7C486', '7C489', '7C490', '7C491', and '7C492'. To display these values in a Dropdown wit ...

"div p" or "div * p"? Do they have the same meaning or is there a difference between them?

My knowledge of the "grandchild" selector in CSS was limited until I came across this insightful article. Intrigued, I decided to experiment with it and found that it resembles the universal selector (which targets all elements). Let's take a look at ...

How to Use AJAX to Read a Text File in JavaScript

Having trouble with AJAX! I have successfully set up a marquee on my website, but now I want it to dynamically fetch the text from a text file. The goal is to read the text from the file (which contains only one line) and assign it to a global variable nam ...

AngularJS: Move forward with controller execution after completion of a looped service method

Currently, I am implementing a networkService in Angular which is responsible for looping while the internet connection is unavailable. The goal is to resume execution once the connection is restored. Below is an example of a controller: MyApp.controller ...