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

Oops! An error occurred while trying to load the myApp module. The module 'ui.bootstrap' is missing and causing the failure

When using Firefox, I encountered the following error: SyntaxError: syntax error xml2json.js:1 SyntaxError: syntax error ui-bootstrap-tpls-0.13.0.js:1 Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:modulerr] Failed to in ...

The AjaxPoller object is not defined and causing a TypeError

I have a piece of JavaScript code that handles AJAX requests and updates the DOM: this.AjaxHandler = { sendRequest: sendRequest, fetchDataForElement: fetchDataForElement, handleJsonResponse: handleJsonResponse, checkProgress: checkProgress }; fun ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

PHP mail function does not properly align HTML table outputs

After fetching data from the database and inserting it into an HTML table, everything appears fine. However, upon pressing the send button to email the content, sometimes the alignment of the HTML table is disrupted in the email. It seems like specific col ...

Having trouble getting CSS Animation to work in a React project?

I am currently developing a Next.js application using React. const partyButton = useRef(null) const handleParty = () => { setTimeout(() => { partyButton.current.classList.add('party-time'); console.log(party ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

Tips for preventing text wrapping in off-canvas design

Seeking advice for my Web Application prototype - looking to prevent text wrapping in off-canvas menu paragraphs using CSS or JS. New to building this type of menu, I used an example from W3Schools to achieve the current design. <!DOCTYPE html> ...

Transforming user-entered date/time information across timezones into a UTC timezone using Moment JS

When working on my Node.js application, I encounter a scenario where a user inputs a date, time, and timezone separately. To ensure the date is saved without any offset adjustments (making it timezone-independent), I am utilizing Moment Timezone library. ...

Resolving a CSS Layout Dilemma: How to Overlay Sidebar on Wrappers

I've run into a challenge while attempting to position a sidebar over page wrappers. The issue with absolute positioning arises when the sidebar needs to align with the corner of the blue header. I have contemplated using JavaScript to maintain its cu ...

Save this page for later by using JavaScript to create a

Does anyone have a solution as to why window.location.href does not save the current webpage URL as a bookmark? Thank you ...

Donut chart in SVG format failing to display properly in email messages

Here is an example of a donut chart that I am working with: <div class="donut-chart" style="position: relative;"> <svg width="100%" height="100%" viewBox="0 0 42 42" class="donut"> ...

Using HTML and CSS to implement a broadened perspective for a specific design

https://i.stack.imgur.com/ckQHa.png Hello, I am facing an issue with a UX design that is optimized for 1200px resolution width. However, when the HTML is loaded in a browser on a larger window resolution, there is a 200px gap on the right side. How can I ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

What is the reason for Cloud Firestore's realtime database fetching all items?

Currently, I am developing a project with vuejs and I am facing an issue where I need to fetch only the last created item from Firestore's realtime database. However, when I execute the following code snippet, it retrieves all items from the database ...

Ways to automatically run Java script again when new elements are included in the document model

Recently, I added paging and filtering to a page displaying a list of products. @model ProductFiltersViewModel ... <div class="row"> <aside class="col-3"> <nav class="sidebar card py-2 mb-4"> ...

Every time Fetch() is called in Node.js, a fresh Express session is established

Here is a snippet of code from a webshop server that includes two APIs: ./login for logging in and ./products to display products. The products will only be displayed after a successful login. The server uses TypeScript with Node.js and Express, along wit ...

Is there a way to retrieve the id of the parent element containing the PHP code using PHP?

I need to verify if the php code being executed is located within a div named "parent2". Currently, I am customizing a Joomla HTML override and attempting to place one module in two different positions. If the module is contained within parent2, then spe ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

Is it necessary for React components to be organized in a hierarchy?

In all my years, I've been told that React components should follow a tree hierarchy so that parent components can manage state and pass it down to their children. But is this truly necessary? The guiding principle of React states that "React has bee ...

Opera browser encountering issue with styled image overlay in select list

We have implemented images in CSS to customize our select fields and they appear correctly in most browsers, except for Opera where the images are not displaying. To better illustrate the issue, I have set up a JSfiddle. Please try it out in Opera to expe ...