What Is Preventing Fields from Being Filled in the Drop-Down Menu?

Looking to achieve this outcome: https://jsfiddle.net/nstruth/t0dopzav/1/

The issue I'm facing is that the HTML appears correctly when Volvo is selected, but the JavaScript is not functioning as expected. Despite reviewing similar innerHTML JavaScript queries, I still find it confusing. Here's a JSFiddle where the units aren't populating as intended: https://jsfiddle.net/nstruth/ksgwaqc8/8/

// Your Javascript code here
$(document).ready(function() {
  $("#cars2").select2();
});

//Distance Math

var units = [
  ['Inches', 0.025400000000000],
  ['Feet', 0.30480000000000000],
  ['Furlongs', 201.168]
];
var selectors = document.querySelectorAll('.newClass1');

for (var i = 0; i < units.length; i++) {
  for (var j = 0; j < selectors.length; j++) {
    var option = document.createElement('option');
    option.value = units[i][1];
    option.textContent = units[i][0];
    selectors[j].add(option);
  }
}

function calcLength1() {
  var SpecialValue = document.getElementById("lengthInput1").value * document.getElementById("lengthCalc1").value / document.getElementById("lengthCalc2").value;
  document.getElementById("lengthInput2").value = SpecialValue.toFixed(12);

}

function calcLength2() {
  var SpecialValue = document.getElementById("lengthInput2").value * document.getElementById("lengthCalc2").value / document.getElementById("lengthCalc1").value;
  document.getElementById("lengthInput1").value = SpecialValue.toFixed(12);
}

function myFunction(event) {
  var x = document.getElementById("myDIV");
  // Selecting an option
  var y = $('select#cars2 option:selected').val();
  switch (y) {
    case '1':
      x.innerHTML = `<p>From:</p>
                                    <select style="float:left" id="lengthCalc1" class="js-example-basic-single select2-container newClass1" oninput="calcLength1()" onchange="calcLength1()">
    </select>

                                    <input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput1" type="number" oninput="calcLength1()" onchange="calcLength1()" />

                                    <p>To:</p>

                                    <select style="float:left" id="lengthCalc2" class="js-example-basic-single select2-container newClass1" oninput="calcLength2()" onchange="calcLength2()">   
  </select>

                                    <input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput2" type="number" oninput="calcLength2()" onchange="calcLength2()" />`;

      $(".js-example-basic-single").select2();
      break;
    case '2':
      x.innerHTML = "<p>Roy!</p>";
  }
}
select {
  width: 150px;
}

.select2-selection--single {
  height: 100px !important
}

/* Other CSS rules go here */

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89faece5eceafdbbc9bda7b8a7b9a4fbeaa7b9">[email protected]</a>/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b4a2aba2a4b3f587f3e9f6e9f7eab5a4e9f7">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
<div id="myDIV">
  <p>Hello</p>
</div>

<label for="cars">Choose a car:</label>

<select id="cars2" onchange="myFunction()">
  <option value="0">Pick something</option>
  <option value="1">Volvo</option>
  <option value="2">Saab</option>
  <option value="3">Opel</option>
  <option value="4">Audi</option>
</select>
<script>
/* Additional scripts can be added here */
</script>

Answer №1

I successfully tackled my issue using the combination of display:none and jQuery. Take a look at this demonstration on JSFiddle to see how I achieved it: https://jsfiddle.net/nstruth/482sgxcu/9/

Here is the HTML snippet:

<!DOCTYPE html>
<html>
<head>
<script   src="https://code.jquery.com/jquery-3.6.0.min.js"  ></script>
<link href="https://cdn.jsdelivr.net/npm/example/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="STYLE.css">
<script src="https://cdn.jsdelivr.net/npm/example/dist/js/select2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function() {
$('#cars2').select2();
$('#cars2').select2('open');
});
</script>

<style>..
select {
width: 150px;
}
</style>
</head>
<body>
<div id="myDIV"><p>Hello</p></div>

<label for="cars">Choose a car:</label>

<select id="cars2">
<option value="red">Pick something</option>
  <option value="yellow">Volvo</option>
  <option value="blue">Saab</option>
  <option value="3">Opel</option>
  <option value="4">Audi</option>
</select>
<script>
    $(function() {
        $('#cars2').change(function(){
            $('.colors').hide();
            $('#' + $(this).val()).show();
        });
    });
</script>
<div id="yellow" style="display:none">
<p>From:</p>
  &nbsp&nbsp<select style="float:left" id="MetricAndImperialLength1" class="js-example-basic-single select2-container newClass1 colors" oninput="Run1()" onchange="Run1()"></select>

  <input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000" id="Input1" type="number" oninput="Run1()" onchange="Run1()">

  <p>To:</p>

&nbsp;&nbsp;  <select style="float:left" id="MetricAndImperialLength2" class="js-example-basic-single select2-container newClass1" oninput="Run2()" onchange="Run2()"></select>

  <input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000" id="Input2" type="number" oninput="Run2()" onchange="Run2()" /></div>
<script src="mathandstuff.js"></script>
<script>
$(".js-example-basic-single").select2();
</script>
</body>
</html>

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 Facebook comment section is taking control

<div class="fb-comments" data-href="https://www.facebook.com/pages/Societ%C3%A0-Ginnastica-Triestina-Nautica/149520068540338" data-width="270" data-num-posts="3"> I'm having trouble with the comment box extending past my div height and overlapp ...

Caution: Additional server attributes detected: style

Alert in my Next.js project, I encountered the following message: Notice: Server is sending additional attributes: style I am uncertain about the source of this warning and therefore unable to provide any code snippet. ...

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Strange behavior observed while attempting to create a smooth CSS transition effect from the right side

Is there a way to create a hover effect in my navbar where a line appears from the bottom left and top right, without causing any size or alignment issues with the links? * { margin : 0; padding: 0; } nav{ background-color: black; width: 1200px; he ...

What is the process of acquiring JSON and converting it into a JavaScript object array?

Can someone please assist me in converting the JSON generated in Spring Boot into a JavaScript object array? I'm currently facing some difficulties. https://i.stack.imgur.com/Tx5Ri.png I've been using XMLHttpRequest and my JS code is as follows ...

Finding the total amount in VueJS2

I'm having trouble calculating the total row in Vuejs2 as shown in the image below: This is the code I have been using: <tr v-for="(product, index) in form.items" :key="index"> <td class="saleTable--td">{{ product.name }}</td& ...

Updating a JSON file with new object using node.js

Currently, I am attempting to insert a single object into an extensive JSON file. My approach involves parsing the entire file using FS and JSON.Parse, adding the new JSON object in memory, and then rewriting the file. While I am aware of FS's append ...

When you scroll through the page, white blocks suddenly appear

After completing a website, I noticed some white blocks appearing when scrolling. You can view the site here. This issue occurs on both mobile and desktop devices during the initial load only. Could this indicate that the page has not fully loaded yet? If ...

iOS SDK - The Ultimate Tool to Unlock HTML 5 Player

Currently, I am facing a challenge while using Hpple to extract links from webpages. Due to the lack of support for Flash on iOS, I have to resort to the HTML 5 player. My objective is to locate and access this player. In scenarios where the website loads ...

Transmitting live video to rtmp using the client's web browser

Is it feasible to stream video from a client browser to an RTMP server without using Flash? I am searching for an alternative solution. https://github.com/ahyswang/actionscript-publisher I found this to be effective, but it relies on Flash. Do I need to ...

data.map` does not work as a function

I've encountered a persistent error that has me stumped. Here's the code snippet: JSON {"inventory": [ { "item_id" : "123", "item_data" : { "image_id" : "1234", "description" : "foo", "lin ...

Retrieve data from a MySQL database with multiple values stored in a single row

In my project, I have implemented a filter functionality using PHP and jQuery/AJAX, where my table of products is structured as follows: |id|status|name|colors_id| ------------------- | 1| 1 | toy| 1,4,7 | <-- these are the IDs of various filters, ...

What could be causing a Bootstrap JavaScript error to appear within my Chrome Extension?

I am currently working on developing a Chrome extension that will display a button on Google's search results page, and when the user hovers over the button, a modal window will appear. While I have been able to make the modal window partially appear ...

Encountering an error with NextJs & Strapi when utilizing the getStaticPaths functionality

Currently, my project involves using Strapi to develop a custom API and NextJs for the frontend. I am experimenting with utilizing getStaticPaths to generate pages based on different categories. In Strapi, I have set up a collection for categories that is ...

Upon loading the React Login page, the focus immediately shifts to the 'password' field rather than the 'username' field

I am currently in the process of building a login page using React. The code below is from my input.jsx file where I have imported Bootstrap components. import React from "react"; const Input = ({ name, label, value, onChange, error }) => { ...

Looking to grasp the concept of calling inline functions within a React functional component

As a newcomer to React, I recently created a new view within my company. Following the example of many guides, I have utilized inline functions and function components exclusively. One common practice I have adopted is writing onClick events in this manne ...

Require assistance with handling Ajax when a function with an Ajax call is repeatedly invoked

I am seeking guidance with ajax as I am still new to it. A problem arises when the same ajax call is made multiple times before the previous one completes its execution, resulting in an empty pop-up on the user interface. How can this issue be resolved? Es ...

Is it true that SPFx doesn't support JQuery?

Currently, I am in the process of developing a new SharePoint Web Part using SPFx generated by Yeoman. The scaffolding template is working well and I have encountered no issues adding NPMs for JQuery and JQueryUI. As I run GULP SERVE, everything seems to b ...