Issue with DOM: inability to detect value changes in vanilla JavaScript

I'm having an issue with my dropdown functionality. When I select "USA", the options should show states such as Washington, Texas, and New York. However, after selecting Texas, only Washington is displayed as the first value instead of Texas in the div element. I want to find a solution without using JQuery. Can anyone help?

function random_function() {
  var name = document.getElementById("output").value;
  document.getElementById("district").innerHTML = name;
  var a = document.getElementById("input").value;
  if (a === "INDIA") {
    var arr = ["Maharashtra", "Delhi"];
  } else if (a === "USA") {
    var arr = ["Washington", "Texas", "New York"];
  }

  var string = "";

  for (i = 0; i < arr.length; i++) {
    string = string + "<option>" + arr[i] + "</option>";
  }
  document.getElementById("output").innerHTML = string;
  var name = document.getElementById("output").value;
  document.getElementById("district").innerHTML = name;
}
<select id="input" onchange="random_function()">
  <option>select option</option>
  <option>INDIA</option>
  <option>USA</option>
</select>
<div>
  <select id="output">
    <option></option>
  </select>
</div>
<div>
  <p id="district" onchange="random_function()"></p>
</div>

Answer №1

If your requirement is to showcase the chosen location from the select submenu when clicked, here is one way to achieve it:

Check out this alternative method:

 function random_function() {
      var a = document.getElementById("input").value;
      var arr; // Make sure arr is accessible outside if else blocks...
      if (a === "INDIA") {
        arr = ["Maharashtra", "Delhi"];
      } 
      if (a === "USA") {
        arr = ["Washington", "Texas", "New York"];
      }
      // Clear array selection on choosing "select option"
      if (a === "select option") {
         arr = [];
      }
    
      var string = "";
    
      for (i = 0; i < arr.length; i++) {
        string = string + "<option>" + arr[i] + "</option>";
      }
      
      document.getElementById("output").innerHTML = string;
      
      // Reset displayed result upon state change...
      var district = document.getElementById("district");
      district.innerHTML = "";
    }
    
    // Show selected city when user clicks in submenu
    function display() {
      var district = document.getElementById("district");
      var value = document.getElementById("output").value;
      district.innerHTML = value;
     
    }

Here's the jsbin test link for reference.

Answer №2

To achieve the desired result, it is necessary to update the value of your #district each time either of the dropdown menus changes. A separate function can be created for this purpose:

function updateDistrict() {
  var country = document.getElementById("country").value;
  var state = document.getElementById("state").value;

  if (country === "INDIA") {
    var districts = ["Maharashtra", "Delhi"];
  } else if (country === "USA") {
    var districts = ["Washington", "Texas", "New York"];
  } else {
    var districts = [];
  }

  var districtOptions = "";

  for (var i = 0; i < districts.length; i++) {
    districtOptions += "<option>" + districts[i] + "</option>";
  }

  document.getElementById("district").innerHTML = districtOptions;
}

function showSelectedDistrict() {
  var selectedDistrict = document.getElementById("output").value;
  document.getElementById("district").innerHTML = selectedDistrict;
}
<select id="country" onchange="updateDistrict()">
  <option>Select Country</option>
  <option>INDIA</option>
  <option>USA</option>
</select>
<div>
  <select id="state" onchange="updateDistrict()">
    <option></option>
  </select>
</div>
<div>
  <p id="district" onchange="showSelectedDistrict()"></p>
</div>

Answer №3

Make sure to include a value attribute within the option tag.

<option value="Canada">Canada</option>

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

JavaScript script that parses innerHTML

Does the behavior of element.innerHTML = '<script>alert()</script>'; differ across browsers? Can I consistently expect innerHTML to not parse scripts? ...

Error in Node application: Cannot search for 'x' in 'y' using the 'in' operator with Express and Nunjucks

Hello everyone, I am a beginner in the world of Nunjucks/Express and Node.js. I have a routes file that is capturing the value of an input from a form field. My goal is to check if this value contains the string 'gov'. Here is what my code look ...

What purpose does AJAX / AJAJ serve in Sails Express JS apart from facilitating asynchronous processing?

When considering practicality, what are the strengths and weaknesses of using AJAX or AJAJ in comparison to other standards like HTML post followed by: res.render('returnView', {outputVariable: V }) Does it matter if processing the input takes ...

Sending dynamic object information to a component through nuxt-link

I've developed a project in Nuxt 3 that features a homepage displaying various products. Users can click on the product title to access the details page, achieved through the use of <NuxtLink> <NuxtLink :to="{ name: 'slug', par ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Ways to prompt the user to upload a file and integrate it into my program

Hello everyone, I need some help figuring out how to replace a JSON file with another JSON file that a user uploads. Here is my JavaScript code: var app = angular.module('miApp', []); app.controller('mainController', function ($scope ...

Unable to extract property from object in context due to its undefined status

Having trouble with the useContext hook in my React app for managing the cart state. Keep getting an error stating that the function I'm trying to destructure is undefined. I'm new to using the context API and have tried various solutions like e ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Eliminate a descendant of a juvenile by using the identification of that specific juvenile

Here is the current structure I'm working with: https://i.sstatic.net/TejbU.png I want to figure out how to eliminate any field that has the id 3Q41X2tKUMUmiDjXL1BJon70l8n2 from all subjects. Is there a way to achieve this efficiently? admin.databa ...

Navigating the itemlist HTML to extract and manipulate data in a Flask application

In my current project, I am attempting to retrieve a value from an array in Flask based on the user's selection. Additionally, I need to perform calculations on this value within Flask as well. Below is the code snippet: HTML Code: <div class="f ...

What steps does VSCode take to ensure that all necessary node dependencies are installed for its extensions?

As I work on constructing my own pluggable application, I've been curious about how vscode handles its extensions' dependencies. Does it run npm install in each extension directory and utilize those installations individually? Or does it have a c ...

Customizing Date Format for Multiple Datepickers on a Single Page using Angular Material (md-datepicker)

I am currently working with angular material and using md-datepicker. My goal is to be able to set different date formats depending on the user's selection. For example, if the user chooses 'daily', I want the datepicker to display 'MM/ ...

"Customizing FusionCharts: A step-by-step guide to changing the background color

Is there a way to modify the background color of fusionchart from white to black? Additionally, how can I change the font color in the chart? https://i.sstatic.net/MMuIq.png ...

How to add data to Laravel after successful ajax request

I have a div containing bids: @foreach($bids as $b) <div class="bids notice notice-lg"> <strong>{{$b->user->name}}</strong> is offering <span style="font-size: 18px" class="label label-success">{{$b->bid}} €</span ...

Navigate to the top of the page prior to updating the Link route in NextJS

Whenever I click on a link to navigate to a new page, the page loads and immediately scrolls to the top. I want to change this behavior so that the scroll resets to the top before the new page is rendered. You can observe this issue on . If you scroll do ...

Iterating through an array in Angular with ng-repeat and dynamically adding two elements to a div instead of just one

Utilizing Angular, I have set up a get request to retrieve live data. My goal is to then showcase this data on the home page. Here is the code snippet from my controller: $scope.holder = []; $http.get('url').success(function(data){ $sc ...

Utilizing Jquery for transmitting and receiving data

As a newcomer to application development, I have been struggling with figuring out how to send and retrieve data using the latest version of JQuery. My main concern is ensuring that the functionality I implement is compatible with all browsers. While I ha ...

React: segregate state and functions away from the view, although encountering an excess of props to transmit

Experimenting with a new approach that keeps state definition and functions separate from components. For example: // Display.js const Display = (props) => { const { data, setData, action } = props; ... return <div>...</div>; } // Di ...

How can I create 3 conditions in an AJAX request to verify a user's ID?

I am trying to create 3 conditions in Ajax to check when creating a new user id. It works for 2 conditions (username can be used and username is already in use), but I encounter a problem when the user leaves the username field empty, and it still displays ...

Tips for avoiding axios from making a post request before the state is properly updated

I'm encountering an issue where the post request doesn't send the updated currentVideo state because setState appears to be non-blocking. Is there a way to make axios wait for the state to be set before making the post request? const nextVideo = ...