Choose an option from the dropdown menu in the form

I am looking to design a form field with options that display additional fields when a specific option is chosen.

<div class="col-md-12">
  <label for="event" class="form-label"
    >Do you have more details about your event</label
  >
  <select id="event" class="form-select">
    <option
      value="choose"
      selected
      aria-label="Disabled select example"
      disabled
    >
      Please choose
    </option>
    <option value="no">No</option>
    <option value="yes">Yes</option>
  </select>
</div>

<div class="col col-md-4 extended">
  <label for="eventtype" class="form-label"
    >Type of Event</label
  >
  <input type="text" class="form-control" id="eventtype" />
</div>
<div class="col col-md-4 extended">
  <label for="guests" class="form-label"
    >Number of Guests</label
  >
  <select id="guests" class="form-select">
    <option
      selected
      aria-label="Disabled select example"
      disabled
    >
      Please choose
    </option>
    <option>30 - 100</option>
    <option>100 - 200</optioin>
    <option>more than 200</option>
  </select>
</div>
<div class="col col-md-4 extended">
  <label for="duration" class="form-label"
    >Duration of Performance</label
  >
  <input type="text" class="form-control" id="duration" />
</div>
<div class="col col-md-6 extended">
  <label for="place" class="form-label">Location</label>
  <input type="text" class="form-control" id="place" />
</div>
<div class="col col-md-6 extended">
  <label for="date" class="form-label">Date</label>
  <input type="date" class="form-control" id="date" />
</div>

All the elements within divs having the class name of ".extended" should be hidden when "No" is selected.

I tried writing JavaScript code to achieve this functionality, but I'm only getting the value of "choose" all the time.

var Extended = document.querySelectorAll(".extended")
var selObj = document.getElementById("event");
var selValue = selObj.options[selObj.selectedIndex].value;

console.log(selValue)

if (selValue === "no") {
    Extended.forEach(el=>el.classList.add("visually-hidden"));
}

I have gone through some articles on extracting values from a select element, but my current implementation seems not working. I would greatly appreciate any guidance on identifying the mistake in my code.

Answer №1

Thank you for sharing that valuable tip about using event listeners. I was able to successfully resolve the issue by implementing this code:

var selectedObject = document.getElementById("event");

selectedObject.addEventListener("change", () => {
  var extendedElements = document.querySelectorAll(".extended");
  var selectedValue = selectedObject.value;
  if (selectedValue === "no") 
    extendedElements.forEach(element => element.classList.toggle("visually-hidden"));

})

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

I'm thinking about transitioning my current React app to Next.js. Do you think it's a good move?

We have recently transitioned our project from react-redux with firebase authentication and solr DB to next.js. Below is the updated folder structure of our app: --src --actions --assets --components --controllers --firebase --redu ...

Vue component doesn't update reactively until the template value changes

I have a child component in my Vue application that utilizes Vuex for managing certain values. Currently, when I trigger an action in the parent component, it should also trigger the child component. This is achieved by passing an active boolean prop to t ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Developing novel errors in JavaScript

There are times when I overlook using the await keyword, for example: const foo = bar(); // as opposed to const foo = await bar(); Identifying these bugs can be challenging. Are there any methods, libraries, or tools that can help prevent such errors? ...

Resetting a radio button inside a Vue component

I have implemented a Vue component for creating a dropdown select input. Below is the code for the component: export default { name:"dropdown", template:` <div class="select"> <ul> <li><label><inp ...

Having difficulty executing JavaScript code from the VB code behind

Recently, I have encountered a strange issue while working with ASP/VB.net. In my code behind VB file, I am trying to call a JavaScript function, but it seems like nothing is happening. Surprisingly, I have used a very similar method on several other pages ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

Clicking on a button in HTML to open a JavaScript file

As a beginner in HTML and JavaScript, I am looking for a way to open a JavaScript file when the onclick event of a button in my HTML file is triggered. Can anyone provide me with guidance on how to achieve this? Thank you in advance. ...

Node.js server only supports cross-origin requests for protocol schemes when working with an Angular front end

Struggling to configure CORS on a local site hosting a Node.js server and an Angular client. Encountering the following error: Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been bl ...

Transferring a document to a koa-js server using formidable

Looking for some guidance with my attempted file upload process from my Ionic app to a Node.js server using koajs. I'm currently utilizing koa-body and formidable to parse the body. Below is the configuration on my server: this.app.use(formidable()) ...

Understanding the status of HTTP requests or observing the updates of observables in Angular2/Typescript is essential

I've been working on an Angular2 and Typescript application where I'm utilizing Angular2's HTTP methods to retrieve data from a database within a service. The service is triggered inside a component's onInit() function and I'm able ...

What is the best method to include spacing between strings in an array and then combine them into a csv-friendly format?

The method I am currently employing involves the following: var authorsNameList = authors.map(x => x.FirstName + ' ' + x.LastName); Yet, this generates an outcome similar to this: Bob Smith,Bill Jones,Nancy Smith Nevertheless, the desired ...

Tips for transferring information from an express rendering to a Vue component?

When working with an express route, page.js router.post('/results', (req, res, next) => { output.terms = "hello" output.results = [{"text": "hello world"}, {"text": "hello sunshine"}] res.render("/myview",output) }) The cod ...

Having trouble triggering a click event with JQuery

I have a hidden link for downloading Audio Files that I want the user to access using a button. However, I am having trouble triggering the click event. Below is the HTML code: <a class="APopupDown" data-icon="home" id="DownloadFile" href="http://yaho ...

Live formatting of phone numbers using regular expressions

For my AngularJS project, I am looking to format phone numbers as they are being typed, without relying on any external library. The desired format is: 99 99 99 99 99 var phone = tel.replace(/\D*(\d{2})\D*(\d{2})\D*(\d{2})&b ...

The libmagic library detects the MIME type of files as text/plain rather than text/javascript or

In my web project's interface, I am using libmagic to retrieve the MIME type of a file. Interestingly, I am encountering issues where css and js files are being identified as text/plain MIME type. When using Chromium, the following warnings are displ ...

"Why is it that when using jQuery, the .fail method doesn't accept arguments to deliberately

I am attempting to utilize custom JSON encoded data after intentionally triggering an error on the server (throwing an error on purpose) during a jQuery AJAX request. I am confused as to what is going wrong, as the header is correct and the data is being ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

What is the proper method for terminating an Express app.all?

Here's a snippet of my code where I utilize the app.all method. In this scenario, I am invoking the fetchBuildings function based on the building ID or hash provided in the URL. Subsequently, I am assigning values to the title, description, and image ...

Exploring the latest whatwg-fetch update with TypeScript version 2.5.3

Within my TypeScript project, I am currently utilizing "whatwg-fetch": "2.0.3" as the latest version of this polyfill. Additionally, for types, I am using version "@types/whatwg-fetch": "0.0.33", and everything functions smoothly when working with TypeScri ...