Creating a JavaScript-powered multi-department form: A step-by-step guide

Is there a way to maintain the form displayed on a webpage created in HTML5 and JavaScript for logging calls across three different departments? With buttons assigned to each department, clicking on them reveals the respective HTML form. That said, every time a form is submitted, the page reverts back to the blank default. How can I ensure that the last used department's form remains visible upon submission?

For instance, if a user is using Department 1's form and submits it, the page should reload Department 1's form accordingly. The same logic applies to Department 2 and Department 3 as well.

The current issue requires users to reclick their department to reload the form. Attempts to use triggers like onsubmit or onclick have proven unsuccessful so far.

Below is the provided code:

HTML

<div class="department">
   <input type="button" class="DeptTitle" value="Department 1" onClick="return changeDept1()" />
   <input type="button" class="DeptTitle" value="Department 2" onClick="return changeDept2()" />
   <input type="button" class="DeptTitle" value="Department3" onClick="return changeDept3()" />
</div>
<div class="body" id="default"></div>
<div class="body" id="Dept1"><form id="calllog" action="" method="post"><input type="Submit" value="Submit" /></form></div>
<div class="body" id="Dept2"><form id="calllog" action="" method="post"><input type="Submit" value="Submit" /></form></div>
<div class="body" id="Dept3"><form id="calllog" action="" method="post"><input type="Submit" value="Submit" /></form></div>

CSS used to hide and show the departments:

/* Different Departments, hides all but default */

#default {display: block;}
#Dept1 {display: none;}
#Dept2 {display: none;}
#Dept3 {display: none;}

Finally, the JavaScript code facilitating switching between forms:

function changeDept1() {
document.getElementById('default').style.display = "none"; // hide default div tag
document.getElementById('Dept1').style.display = "block"; // show Dept1 Form div tag
document.getElementById('Dept2').style.display = "none"; // hide Dept2 Form div tag
document.getElementById('Dept3').style.display = "none"; // hide Dept3 div tag
}

function changeDept2() {
document.getElementById('default').style.display = "none"; // hide default div tag
document.getElementById('Dept1').style.display = "none"; // hide Dept1 Form div tag
document.getElementById('Dept2').style.display = "block"; // show Dept2 Form div tag
document.getElementById('Dept3').style.display = "none"; // hide Dept3 div tag
}

function changeDept3() {
document.getElementById('default').style.display = "none"; // hide default div tag
document.getElementById('Dept1').style.display = "none"; // hide Dept1 Form div tag
document.getElementById('Dept2').style.display = "none"; // hide Dept2 Form div tag
document.getElementById('Dept3').style.display = "block"; // show Dept3 div tag
}

While the above functions switch forms successfully, maintaining the display post-submission proves challenging. Additional attempts with onsubmit triggers did not resolve this issue effectively.

function showDept1 () {
document.getElementById('Dept1').style.display = "block"; // show Dept1 Form div tag
}

A separate concern involves resetting the form whenever switching departments. If a user fills out one form, then shifts to another department and back, the initial form retains previous input. Is there a relationship between these two issues?

Thank you in advance for your assistance!

Answer №1

Forget about using JavaScript and opt for named anchors instead.

Take a look at my CodePen which contains the essential code you'll need: http://codepen.io/aardrian/pen/OPgmPe

If you want to see it in action, here are the links showing each of the three options (you can customize this to use elements other than a list):

You can then simply submit each form (since you already have three <form> elements) to the URL with the correct named anchor, which essentially follow the URLs provided above.

No JavaScript is needed.

The CSS code:

.expando {
  display: none;
}

.expando:target {
  display: block;
}

The HTML code (including content):

  <ul>
    <li><a href="#Expando1">The Tick</a>
      <ul class="expando" id="Expando1">
        <li>Has superhuman strength and mass;</li>
        <li>Is nigh-invulnerable; </li>
        <li>Has powers that increase as the situation becomes more dramatic;</li>
        <li>Does not seem to require oxygen;</li>
        <li>Cannot keep his balance if his antennae are removed.</li>
      </ul>    
    </li>
  </ul>

  <ul>
    <li><a href="#Expando2">Sewer Urchin</a>
      <ul class="expando" id="Expando2">
        <li>Has slime &amp; stench secreting spikes on his suit enable him to stick on any surface;</li>
        <li>Is equipped with lemon grenades, butter shooters, bars of soap and other various apparel to aid him in his underground endeavors; </li>
        <li>Has an oxygen tank and mask which enable him to breath in the thickest of sewer sludge;</li>
        <li>Has a submarine that he garbage-picked.</li>
      </ul>    
    </li>
  </ul>

  <ul>
    <li><a href="#Expando3">Arthur</a>
      <ul class="expando" id="Expando3">
        <li>Has a suit that enables wobbly flight;</li>
        <li>Has an accounting background.</li>
      </ul>    
    </li>
  </ul>

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

Change icons in Ionic 5 when selecting a tab

How can I change my tab icons to outline when not selected and filled when selected? The Ionic 5 Tabs documentation mentions a getSelected() method, but lacks examples on its usage. I plan to utilize the ionTabsDidChange event to detect tab clicks, then ...

Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or ...

Update the link by simply clicking on a div tag

I am currently working on a PHP page and my goal is to add the extension ?id=variable_value to its URL when I click on a specific div. However, whenever I try to do this, it shows me an error message stating that the URL with the extension is undefined. B ...

The translateX property will be set to the offsetX value of the event when the mouse is moved, resulting in a

Here's a quick and easy question regarding some kind of scrubber tool. Check out the fiddle below. When using jQuery to bind to the mousemove event and adjusting the transformX property in the positive direction, there's a 50% chance it will ret ...

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

Utilizing jQuery to apply a class to an element and modify the CSS parameters with custom values simultaneously

Unsure if this idea is feasible, but I'll attempt to explain my requirements. I am interested in accomplishing something like the following: A CSS class with variables X, Y, and Z left undefined: .r {border-radius:Xpx;-webkit-border-radius:Ypx;-moz ...

How can checkboxes be combined from two separate tables?

Within this interactive code example, you will find two tables containing checkboxes in each row. Upon clicking the To button, a dialog box will appear allowing you to select users or groups from a drop-down menu. The corresponding tables will then be dis ...

Save the Selenium HTML source code into an HTMLDocument element

Is there a way to save the HTML code fetched using Selenium (via Excel VBA) into an HTMLDocument element? The following example demonstrates utilizing Microsoft Internet Controls and Microsoft HTML Object Library for automating Internet Explorer. Dim IE ...

Arranging elements in two arrays in either ascending or descending order

Looking to implement sorting functionality for the "fuel.name" value within this array... const orders = [ { "_id":"5d14a31490fb1e0012a3d2d8-1", "orderId":"0JL5ORM0JT-1", "created":"2019-06-27T11:05:56.377Z", "createdDate":"2019-06-2 ...

How to insert text into a text input using onKeyPress in react.js

I am looking to simulate a typing effect where the phrase 'Surveillance Capitalism' is inputted letter by letter into a text input field as a user types. However, I encounter an issue when trying to add each individual letter into the input; I re ...

Creating objects that are a fraction of another's width

My goal is to create 3 responsive divs that fill the width of the window and adjust their width based on the window dimensions. However, I'm facing an issue with JavaScript where it seems to be miscalculating the window width, causing the objects to o ...

Tips for creating a dynamic curved SVG path

I'm looking to draw a black border only along the inside of this SVG. I've tried adding stroke and setting the stroke-width, but that applies the border to the entire SVG. Is there a way to limit the stroke to a certain point within the SVG? d ...

Assign the appropriate label to the HTML checkbox based on the value obtained from the function

I have managed to successfully initiate the HTML service and display the checkbox itself. However, I am facing a challenge in displaying text next to the checkbox as a label. My goal is to have this label text be the return value of a function in the .gs f ...

Tips for displaying a placeholder image within the Next.js image component

I am currently facing an issue with displaying images from API calls. To handle situations where there are no images or errors, I have implemented a code snippet which includes a placeholder image. However, the implementation seems to not be functioning as ...

Tips for showing text on top of a responsive image using CSS

I am working on a layout with 4 columns, each containing images of different sizes followed by a hover effect with an absolutely positioned mask. The width of the mask is currently exceeding the width of the images. Is there a way to ensure that the mask ...

Is there a way to retrieve the `this.$route` data while using vue-apollo?

Currently working on building a GraphQL query with vue-apollo and graphql-tag. When I manually set the ID, everything runs smoothly. However, I'm aiming to dynamically pass the current route's ID as a variable to Vue Apollo. Successful Implemen ...

Headers cannot be set once they have already been sent in NodeJS

Here is the code where I authenticate users in a group, push accounts into an array, and save them using a POST request on /addaccount. groupRouter.post('/addaccount', Verify.verifyOrdinaryUser, function(req, res, next) { Groups.findById(req.bod ...

Is it not possible to call a function directly from the controller in AngularJS?

I have been trying to update a clock time displayed in an h1 element. My approach was to update the time by calling a function using setInterval, but I faced difficulties in making the call. Eventually, I discovered that using the apply method provided a s ...

Ensuring the aspect ratio of images stays consistent within a flexbox using CSS

How can I create a grid of images without any spacing in between them? I want the width to be 100% of the parent element and each column to have the same size, for example, 20%. Using flex takes care of the columns, but I'm struggling with making the ...

Tips for successfully integrating .dae files into three.js for online execution on a web browser

Hey everyone, I'm an HTML developer who has never worked with WEBGL technology before. I've been trying to figure out how to pass a .dae file into 'three.js' by searching through numerous websites, but I haven't been successful. C ...