Concealing an HTML form field until a dropdown selection is made

I have been struggling with my JavaScript code, searching for a solution to hide a form option (label and textbox) until a value is selected from a dropdown. Specifically, I want to hide the label and input box for "lookup" until a value is selected from the "column" dropdown. Despite my efforts, I can't figure out what the issue is.

Here is my current attempt:

function showDiv(divId, element) {
  document.getElementById(divId).style.display = element.value === "" ? 'table-row' : 'none';
}

var data = {
  "coh_mst": ["AUDIT_ID", "AUDIT_TimeStamp", "..."],
  ... // more data here
};

window.onload = function() {
  var tableSel = document.getElementById("table");
  var columnSel = document.getElementById("column");
  var lookupSel = document.getElementById("lookup");
  for (var x in data) {
    tableSel.options[tableSel.options.length] = new Option(x, x);
  }
  table.onchange = function() {
    columnSel.length = 1;
    var z = data[this.value];
    for (var i = 0; i < z.length; i++) {
      columnSel.options[columnSel.options.length] = new Option(z[i], z[i]);
    }
  }
}
form {
  display: table;
}

p {
  display: table-row;
}

label {
  display: table-cell;
}

input {
  display: table-cell;
}

hideMe {
  display: none;
}
<form action="pageToVisit">
  <p>
    <label for="table">Choose a table:</label>
    <select name="table" id="table" required>
      <option value="" selected="selected">Select a Table</option>
    </select>
  </p>
  <br><br>
  <p>
    <label for="column">Column to Filter:</label>
    <select name="column" id="column">
      <option value="" selected="">Please Select a Table First</option>
    </select>
  </p>
  <br><br>
  <p id="hideme">
    <label for="lookup">Lookup Value:</label>
    <input type="text" id="lookup" name="lookup" value="" onchange="showDiv('hideMe', this)">
  </p>
  <br><br>
</form>

Thank you in advance for any advice provided!

Answer №1

There is a small mistake in the paragraph's id that contains the hidden input. It should be id="hideMe" to match the CSS and the call to showDiv().

The showDiv() function should not be in the onchange event of the hidden input, it should be in the previous dropdown.

The condition in the showDiv() function is incorrect. It should show the element when the dropdown's value is not empty.

function showDiv(divId, element) {
  document.getElementById(divId).style.display = element.value !== "" ? 'table-row' : 'none';
}

var data = {
        // Here is a long list of data objects
 }

window.onload = function() {
  // code for populating dropdown options dynamically
}
form {
  display: table;
}

p {
  display: table-row;
}

label {
  display: table-cell;
}

input {
  display: table-cell;
}

#hideMe {
  display: none;
}
<form action="pageToVisit">
  <p>
    <label for="table">Choose a table:</label>
    <select name="table" id="table" required>
      <option value="" selected="selected" disabled>Select a Table</option>
    </select>
  </p>
  <br><br>
  <p>
    <label for="column">Column to Filter:</label>
    <select name="column" id="column" onchange="showDiv('hideMe', this)">
      <option value="" selected="">Please Select a Table First</option>
    </select>
  </p>
  <br><br>
  <p id="hideMe">
    <label for="lookup">Lookup Value:</label>
    <input type="text" id="lookup" name="lookup" value="">
  </p>
  <br><br>
</form>

Answer №2

Yes, I have completed that task and it may prove to be beneficial.

const data = 
  { coh_mst      : ['AUDIT_ID', 'AUDIT_TimeStamp', 'AUDIT_UID', 'AUDIT_RecType', 'AUDIT_TransId', 'site_ref', 'type', 'co_num', 'est_num', 'cust_num', 'cust_seq', 'contact', 'phone', 'cust_po', 'order_date', 'taken_by', 'terms_code', 'ship_code', 'price', 'weight', 'qty_packages', 'freight', 'misc_charges', 'prepaid_amt', 'sales_tax', 'stat', 'cost', 'close_date', 'slsman', 'eff_date', 'exp_date', 'whse', 'sales_tax_2', 'logifld', 'edi_order', 'trans_nat', 'process_ind', 'delterm', 'use_exch_rate', 'tax_code1', 'tax_code2', 'frt_tax_code1', 'frt_tax_code2', 'msc_tax_code1', 'msc_tax_code2', 'disc', 'pricecode', 'ship_partial', 'ship_early', 'matl_cost_t', 'lbr_cost_t', 'fovhd_cost_t', 'vovhd_cost_t', 'out_cost_t', 'end_user_type', 'exch_rate', 'fixed_rate', 'orig_site', 'lcr_num', 'projected_date', 'order_source', 'convert_type', 'aps_pull_up', 'NoteExistsFlag', 'RecordDate', 'RowPointer', 'charfld1', 'charfld2', 'charfld3', 'decifld1', 'decifld2', 'decifld3', 'datefld', 'config_id', 'CreatedBy', 'UpdatedBy', 'Create...
    
label
  { 
  display     : block;
  font-size   : .8em;
  font-weight : bold;
  margin-top  : 1em;
  }
input, select
  { 
  display     : block;
  font-size   : 1em;
  font-weight :normal;
  }
.noDisplay { display : none; } /* use a class ! */
<form action="pageToVisit" name="my-form">
  <label>Choose a table:
    <select name="tableSel" required>
      <option value="" selected disabled>Select a Table</option>
    </select>
  </label>
  <label>Column to Filter:
    <select name="columnSel">
      <option value="" selected disabled>Please Select a Table First</option>
    </select>
  </label>
  <label class="noDisplay">
    Lookup Value:
    <input type="text" name="lookupSel" value="">
  </label>
</form>

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

Why am I unable to view the image in the material-ui-next "Cards" example?

I came across this example on the material-ui-next website, but strangely I am unable to view the lizard image when I try to run it on my computer. Why is the image not showing? There are no errors in my console, and the "simple card" example on the websi ...

Retrieve the corresponding value from an object received from express and display it on a jade template

I'm currently working on a solution to display the correct user information on a page when users navigate to "/users/:name". For example, I want to show "welcome user2" if user2 is logged in. My approach involves passing along the parameter from "/use ...

The issue with res.sendFile is that it is failing to display

I have encountered an issue while attempting to render HTML with res.sendFile using an absolute path. The encoded HTML is being displayed unrendered within a pre tag in the response. Below is the express code I am currently using: app.get('/', ( ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

What is the best method for playing raw audio wav files directly in a web browser?

I'm currently attempting to play wav raw data in the browser that is being transmitted from a Node.js server via socket.io. The main goal is to play the receiving data as quickly as possible without waiting for all the data to be received. I initially ...

axios does not distinguish between response and error in its return value

I have created a React component that contains a function called onFormSubmit. This function calls another function from a separate component, which in turn makes a POST request using axios. I want the ability to return a response if the POST request is su ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...

What methods are available for utilizing a runtime variable that TypeScript is unaware of?

I am looking to implement a global variable in TypeScript that will be defined dynamically at runtime. This global variable is necessary for transferring configuration properties from the server-side language to JavaScript. My approach involves using TypeS ...

How to style a div to center an image vertically with text using CSS

I attempted to vertically align an image next to text within my link. Thus far, I've relied on a background image to achieve perfect vertical centering for the image of my text. CSS .label { margin: 0 0 0 15px; padding: 0; color: #fff; } a.morein ...

Injecting Dependencies Into ExpressJS Routes Middleware

Hey there! I'm currently working on injecting some dependencies into an expressjs route middleware. Usually, in your main application, you would typically do something like this: const express = require('express'); const userRouter = requi ...

Tips for concealing overflowing CSS content

How can I prevent CSS content from overflowing? I am trying to display a price tag in the CSS element, but it is protruding out of my card. .content{ content:''; position: absolute; left: 309px; ...

Nuxt has the ability to display the object itself, however, it cannot render its

I am using a directus API to fetch data, which is returned in an array of objects. I can render the array or an object from it, but not when trying to access a property of the object <template> <div class="grid grid-cols-2 gap-6 mt-6&quo ...

What is the method for extracting an entire space-separated string into a PHP variable from HTML options?

When the select tag fetches options from a MySQL database and assigns a value to a PHP variable for echoing, only the first part of the text is displayed. For example : Option: Vijay Sharma Echo Output: Vijay <select name="facultyname" oncha ...

What are the best practices for utilizing pre-defined CSS classes in Vue.js libraries?

I don't have much experience with CSS, but I'm really eager to customize the appearance of my chart. The chart is generated by a vue.js library and comes with pre-defined CSS classes. However, I'm uncertain about how to access and modify the ...

Failed to perform the action using the Angular Post method

Currently, I am exploring the use of Angular with Struts, and I have limited experience with Angular. In my controller (Controller.js), I am utilizing a post method to invoke the action class (CartAction). Despite not encountering any errors while trigge ...

Step-by-step guide on incorporating edit, update, and discard functionalities within an Angular Material table component (mat-table)

I am currently working on implementing edit, update, and discard functions in an angular material table. While I have been able to successfully edit and update the table row wise, I am struggling with how to discard table rows. If you would like to see wh ...

Unable to locate the tag using .find() function following the use of .attr() method

I am currently utilizing jQuery in conjunction with node-horseman to interact with a specific page. My approach involves referencing the page's data-id attribute, which I then pass to my application to search for the li element containing this attribu ...

Is it possible to utilize `ListBox` provided by `@headlessui/react` alongside Mobx?

Enhancing with ListBox: store/index.ts import { action, makeObservable, observable } from 'mobx' import type { IFrameItStore, TrafficSignal } from '@/types/index' export class FrameItStore implements IFrameItStore { trafficSignal: ...