Having trouble getting Javascript to reveal hidden elements based on their class

I am having some trouble making specific fields in a form appear based on the selection made from a dropdown menu. Below is a simplified snippet of my code, which should change the display from 'none' to 'block'. Can you help me figure out what's wrong with it?

function selectTrain(trainType) {
  document.getElementById("test").innerHTML = (trainType);
  var elements = document.getElementsByClassName(trainType);
  for (var i = 0, length = elements.length; i < length; i++) {
    elements[i].style.display = 'inline-block';
  }
};
<select onchange="selectTrain(this.value)">
      <option value="" disabled="disabled" selected="selected">Please choose a train type</option>
      <option value="lhcs">Loco-hauled carriage set</option>
      <option value="mu">Multiple Unit</option>
      <option value="f">Freight</option>
    </select>

<!-- Form -->

<form name="myForm">
  <p>Formation Information:</p>
  <ul>
    <li class="lhcs f">Locomotive number: <input type="text" id="locoid1"></li>
    <li class="lhcs">Locomotive number: <input type="text" id="locoid2"></li>
    <li class="mu">Formation number: <input type="text" id="formationid">

    </li>
  </ul>

  <p>Names:</p>
  <ul>
    <li class="lhcs f">Locomotive name: <input type="text" id="loconame1"></li>
    <li class="lhcs">Locomotive name: <input type="text" id="loconame2"></li>
    <li class="mu">Formation name: <input type="text" id="formationname"></li>
    <li class="lhcs mu">Train name: <input type="text" id="trainname"></li>
  </ul>

  <p>Train Operating Company:</p>
  <ul>
    <li class="lhcs">Locomotive TOC: <input type="text" id="locotoc1"></li>
    <li class="lhcs">Locomotive TOC: <input type="text" id="locotoc2"></li>
    <li class="lhcs">Carriage TOC: <input type="text" id="cartoc"></li>
    <li class="mu">Formation TOC: <input type="text" id="formationtoc"></li>
  </ul>

  <p>Places:</p>
  <ul>
    <li class="lhcs mu f">Spot or embark point: <input type="text" list="places" id="placeorigin"></li>
    <li class="lhcs mu">Destination: <input type="text" list="places" id="placedest"></li>
  </ul>

  <p>Date and Time:</p>
  <input type="date" id="dateandtime">

  <p>Number of Carriages: </p>
  <input type="number" id="carnum">
  <ul>
    <li class="lhcs mu">Carriage 1: <input type="text" id="carid1"></li>
  </ul>

  <button id='submission' type='button' onClick="goForIt()">Submit</button>
</form>

Answer №1

If you forgot to include the element with id="test" in your DOM, here is an example code snippet for it:

<div id="test"></div>
. Take a look at the snippet below where I have added this div at the end of the page:

 function selectTrain(trainType) {
    document.getElementById("test").innerHTML = (trainType);
    var elements = document.getElementsByClassName(trainType);
    for(var i = 0, length = elements.length; i < length; i++) {
      elements[i].style.display = 'inline-block';
    }
}; 
<select onchange="selectTrain(this.value)">
  <option value="" disabled="disabled" selected="selected">Please select a train type</option>
  <option value="lhcs">Loco-hauled carriage set</option>
  <option value="mu">Multiple Unit</option>
  <option value="f">Frieght</option>
</select>

<!-- Form -->

<form name="myForm">
  <p>Formation Information:</p>
  <ul>
    <li class="lhcs f">Loco number: <input type="text" id="locoid1"></li>
    <li class="lhcs">Loco number: <input type="text" id="locoid2"></li>
    <li class="mu">Formation number: <input type="text" id="formationid">        

    </li>
  </ul>

  <p>Names:</p>
  <ul>
    <li class="lhcs f">Loco name: <input type="text" id="loconame1"></li>
    <li class="lhcs">Loco name: <input type="text" id="loconame2"></li>
    <li class="mu">Formation name: <input type="text" id="formationname"></li>
    <li class="lhcs mu">Train name: <input type="text" id="trainname"></li>
  </ul>

  <p>Train Operating Company:</p>
  <ul>
    <li class="lhcs">Loco TOC: <input type="text" id="locotoc1"></li>
    <li class="lhcs">Loco TOC: <input type="text" id="locotoc2"></li>
    <li class="lhcs">Carriage TOC: <input type="text" id="cartoc"></li>
    <li class="mu">Formation TOC: <input type="text" id="formationtoc"></li>
  </ul>

  <p>Places:</p>
  <ul>
    <li class="lhcs mu f">Spot or embark point: <input type="text" list="places" id="placeorigin"></li>
    <li class="lhcs mu">Destination: <input type="text" list="places" id="placedest"></li>
  </ul>

  <p>Date and Time:</p>
  <input type="date" id="dateandtime">

  <p>Number of Carriages: </p>
  <input type="number" id="carnum">
  <ul>
    <li class="lhcs mu">Carriage 1: <input type="text" id="carid1"></li>
  </ul>

<button id='submission' type='button' onClick="goForIt()">Submit</button>
</form>

<div id="test"></div>

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

The alert box fails to display in the correct orientation when the condition is activated

Currently, I am working on implementing a sign-up feature using PHP. My main goal is to successfully store the user-entered data in MySQL database while ensuring that no duplicate usernames are allowed during account creation. Although everything is functi ...

A collection of asynchronous requests stemming from a sole request

I am facing a unique ajax scenario that is proving to be quite challenging for me. Here is the specific sequence of events that I need to coordinate: An initial request returns an array of ID numbers. A separate request needs to be sent for each ID in ...

Personalize the error message for throwing an exception in JavaScript

I've been working on customizing error messages for exceptions thrown in JavaScript. Despite my best efforts, I have not been successful so far. I'm currently attempting the following code snippet but it's not functioning as expected: f ...

"Receiving the error message 'Object is not a function' occurs when attempting to pass a Node.js HTTP server object to Socket.IO

A few months back, everything was working fine when I set up an HTTPS server. Recently, I revisited the application and decided to switch to HTTP (though this change may not be directly related). In my code snippet below from 'init.js', I create ...

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen. I looked at the Materi ...

Display the list box against the masked background

I currently have a masked background and a drop-down hidden behind it. Here is how it appears: However, I want it to look like this: This is the HTML code being used: <div id="suggest" style="position: fixed; border: 1px solid rgb(168, 168, 168); w ...

Should we store $(this) in jQuery's cache, or leave it be?

When dealing with a selector such as $(this), does the act of creating and reusing a reference actually have a noticeable impact on performance? I find it more efficient to create references for jQuery selectors that are used repeatedly within the same sc ...

Sending data through AJAX

I am currently working on a calendar project. I want to include a description box next to the calendar, where additional information about an event will be displayed when a user clicks on a specific date. Here is what I have so far in terms of HTML/PHP: ...

Steps to transfer selected autocomplete value ID to data attribute using jQuery

I am working on a project where I need to store the State ID in my database instead of the State Name. Currently, I am using an autocomplete query to select the State. How can I pass the selected State's respective ID to the data-attribute of the inpu ...

When incorporating babel-plugin-styled-components, Nextjs may encounter a mismatch error with classnames

After transferring the content of _document.js from the following styled components example and implementing the babel plugin mentioned in the styled components documentation, I am still encountering an error. _document.js import Document from 'next/ ...

Error encountered when processing a PUT request for a node causing a

After receiving minimal views and replies on a similar question I posted last night, I am reaching out again in hopes of resolving my issue. For the past two days, I have been struggling to fix this problem and progress with my project! If you are interes ...

The Android WebView experiencing issues with the functionality of the Hamburger Menu

I'm facing an unusual issue with the Android WebView in my app. The hamburger menu on my website works perfectly fine on my mobile browser, but when I try to open it in the Android WebView, it does not fully expand to show the menu items. I have trie ...

The checkbox labeled "Shipping Same as Billing" is not functioning correctly. I have included my JavaScript code below, can someone please help me identify what I am overlooking? (Only JavaScript code is provided; HTML is

I'm having trouble transferring data from a 'shipping' address to the 'billing' address section. I've included all my code, but nothing seems to copy over when the check box useShip is selected. All the HTML code is provided f ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

I'm feeling a bit lost with this JSON example - specifically with JSON.parse, JSON.stringify, as well as localStorage.setItem

As a beginner in learning JSON, I find that W3schools does not provide clear explanations of what each line of code does. While I can interpret some parts, there are sections that still remain unclear to me. // Data storage process: 1. myObj = {name: "Jo ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...

Is there a way to shift this structure to the right without relying on the float property?

Here's the HTML and CSS I have - .font-size-add-class { background-color: #2f2f2f; color: #f9f7f1; } .font-sizes { text-align: right; display: table; margin-top: 15px; cursor: pointer; } .font-sizes > .small { font-size: 12px; } .font ...