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

Is it possible to customize the notification message displayed after clicking the save button in a listview within ng-admin?

While working on the listview/creation view, I am attempting to incorporate a custom notification message instead of the default one (please see the screenshot) that appears when the user clicks the save button. Is there a way for me to include a custom n ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

Utilizing jQuery to extract the value of a selected list item on click

I have been working on creating a list of items from JSON data and am facing an issue with retrieving the 'data-value' attribute of the clicked item. Here is my current code: const target = $('#list'); target.empty(); for (let i = 0 ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dialog { position: fixed; to ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

Retrieve an array from the updated scope

I need help with my code. How can I retrieve the names from an array and display them in my input box? Also, how do I get all the changed names back into the array? Thanks in advance! - Marco app.js var g[]; var names = ['John', 'Steve&apo ...

Arranging extensive menu sections and content containment

I am currently working on enhancing my website's navigation by creating a mega menu. However, I am facing issues with the organization of the divs containing the ul content. In the fiddle linked below, you can see that "Africa", "Asia", and "Oceania" ...

What steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Find all strings in the array that do not begin with a letter from the alphabet

When a specific button is clicked, I need to filter the example array provided in the snippet below. The expected output should only include elements that do not start with an alphabet. I attempted: const example = ["test", 'xyz', '1 test& ...

Change the position of the specified footer on the one-page website

I am currently in the process of creating a single-page layout website. What I want is to have the elements with the class "footer-bar" positioned absolutely on each page, but on the #Home Page, it should be position relatively. Does anyone have any sugge ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

Leverage the power of npm packages within a Flutter mobile app's webview

I am currently developing a Flutter mobile app and I am interested in incorporating an npm package that utilizes web3.js and offers additional custom features. My understanding is that Dart code in Flutter is not compiled to JavaScript, so I have been lo ...

"Padding has not been recognized as a valid input value

I'm struggling with getting padding to be accepted by the browser when I style a card using Material-UI. const useStyles = makeStyles((theme) => ({ cardGrid: { padding: '20px auto' }, })) Unfortunately, the browser is not recogni ...

How can one discern the most effective method to identify JavaScript code that alters particular HTML content on a webpage?

On my website, I have a <p> tag and I am interested in knowing which JavaScript function is responsible for adding text inside this element. Is there a special method in Chrome to add a listener on this tag and pinpoint the script that writes to it ...

Interact with various contenteditable sections by navigating with the arrow keys

I have a challenge with multiple <p contenteditable="true"></p> elements on my page. I am seeking a solution to enable the use of arrow keys to navigate seamlessly across these separate elements as if they were one cohesive editable element. F ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Steps for configuring mode as 'open' when generating a shadow element with vue-custom-element

Here is the method I used to generate a shadow component Vue.customElement('my-element', MyElement, { shadow: true, shadowCss: mystyles, }); ...

The min-width of 100vh is functioning properly on mobile devices, however, it is not working as expected on PCs when set to 100

When using 100vh, it only works on mobile or if you narrow the width of your web browser on a PC. If the window/width is set at 100%, the image may appear too tall and cause the div class "mars" to overflow the viewport. Unfortunately, screenshots cannot ...

How can I effectively capture a change in the hour using Node.js?

Do you know of a more efficient way to monitor datetime changes instead of checking every 10 minutes, potentially firing nearly 10 minutes late? Any alternative solutions that I may have overlooked for this issue? ...