Tips for selecting and utilizing a drop-down menu in JavaScript

Having an issue with the drop-down list functionality. It seems to only work with the first option selected and not with all of them. Any assistance would be greatly appreciated.

Thank you in advance.

var form1 = document.getElementById('form1');
var form2 = document.getElementById('form2');
var form3 = document.getElementById('form3');

var formArray = [];                     
formArray.push(form1.innerHTML);
formArray.push(form2.innerHTML);
formArray.push(form3.innerHTML);

//select drop down list//

function changeToCal() {
   dropDownList.selectedIndex--;
   document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex];
}

//Calculate // 

document.getElementById('form').addEventListener("submit", 
    function(event) {
        var fieldy = document.getElementById('fieldy');
        var fieldx = document.getElementById('fieldx');
        var resultField = document.getElementById('resultField');

        var x = parseFloat(fieldx.value); 
        var y = parseFloat(fieldy.value); 

        if(!fieldy.value || !fieldx.value) {
        alert("Please enter numbers in the fields!");
        } else if (dropDownList.selectedIndex = 1) {
            var result = (y / 100) * x;
            resultField.innerText = "Answer: " + result + "."
            event.preventDefault();

        } else if (dropDownList.selectedIndex = 2) {
            var result = (100 / y) * x;
            resultField.innerText = "Answer: " + result + "."
            event.preventDefault();
        } else if (dropDownList.selectedIndex = 3) {
            var result = (y / x) * 100; 
            resultField.innerText = "Answer: " + result + " %."
            event.preventDefault();        
        } else {
            resultField.innerText = "Error"
            event.preventDefault(); 
      }

        }
            ); 

https://codepen.io/anon/pen/VMZNwQ

Answer №1

Here's a correction:

} else if (dropDownList.selectedIndex === 1) {

The above line should use a comparison equals operator instead of an assignment equals operator.

A good practice would be to utilize a reliable IDE which can help identify potential errors like this for you.

Additionally, make sure to update the following code snippet:

document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex - 1];

This is necessary to ensure that the selected value is correctly updated when changing the selectedIndex.

Please note that having multiple elements with the same id attribute can lead to unpredictable behavior. It's advisable to keep id attributes unique throughout the document.

Instead of duplicating HTML content, consider using CSS to show/hide forms or updating text dynamically based on the algorithm.

Lastly, consider listening for the click event rather than submit event for regular buttons.

If maintaining multiple forms, it's recommended to register separate button handlers for each form to improve code organization and maintainability.

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

Issue with Jquery's .html() function not functioning properly when trying to select HTML

I am currently working on a piece of code that looks like this: $price = $(element) > $('.main_paket_price').attr('name'); alert($price); Basically, I am trying to select an element inside element which has the class main_paket_pri ...

Tips for loading and updating data simultaneously in VUEJS from a single input

Currently, the data is displayed in a span tag with an input for updating it Is it possible to fetch data from an API, load it into an input field, update the input with new information, and send it back? What are the best approaches for achieving this? ...

How come JavaScript variables are able to persist on JQuery Mobile multi-page templates on desktop browsers, but not on mobile browsers?

My website was created using the jQuery Mobile multi-page template. While testing it on Chrome desktop, I noticed that my JavaScript variables (comics and checkedItems) retain their values when navigating between pages. However, on mobile devices, these ar ...

Unable to set a value for the variable

const readline = require('readline'); let favoriteFood; const rl = readline.createInterface(process.stdin, process.stdout); rl.question('What is your favorite food?', function(answer) { console.log('Oh, so your favorite food is &a ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

Linking asynchronous AJAX requests using Angularjs

Currently in my AngularJS project, I have created a service with multiple functions that return promises. The AJAX Service I've Created: angular.module('yoApp') .factory('serviceAjax', function serviceAjax($http) { return ...

There seems to be a mysterious absence of chuck norris jokes in

I'm attempting to call two different APIs by clicking a button to display a random joke on the screen. I've created two separate functions to fetch the APIs and used Math.random() to generate a random number. If the number is greater than 50, one ...

The API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

Oops! You can only have one parent element in JSX expressions

I'm working on creating a password input box, but I keep encountering an error when integrating it into my JS code. Here's the snippet of my code that includes TailwindCSS: function HomePage() { return ( <div> <p className=&q ...

What is the best way to use a regex to filter the user's input in a Vuetify combobox and generate a chip?

I am working on implementing a restriction for a specific regex pattern while the user types in a combobox to add new chips, such as allowing only phone number chips. Complete Vue Source code: https://codesandbox.io/s/chips-so-0gp7g?file=/src/domains/ex ...

Is there a way to display the contents of a zipped file using an HTML IFrame?

Can I display the contents of a zipped file in an HTML iframe? For example: My_File.pdf.zip contains My_File.pdf. I currently have something like this <iframe src="/path of the folder/My_File.pdf.zip" /> The src attribute points to the zipped file ...

The socket.io client in my JavaScript code is failing to receive the necessary event

Currently, I am in the process of configuring a socket.io chat feature with an expressjs backend and sveltejs frontend. I have established a custom namespace named 'chat' where a new room is generated upon a 'join' request. My appro ...

"I am eager to showcase the text upon pressing the Enter key, implementing an Immediately Invoked Function Expression

My input text box is supposed to store and display the output in an unordered list format when I hit enter. The function works fine without IIFE using onclick event, but it's not working with IIFE. Can anyone assist me with this issue? <html> ...

Acquire a JSON response from a web address by utilizing JavaScript

If you navigate to , you will find a JSON file filled with information about your current geolocation. My goal is to save this JSON data into JavaScript variables, allowing me to manipulate and extract specific fields from the file. ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Tips for automatically loading a new page or URL when a user scrolls to the bottom

I am working on implementing infinite scroll functionality, where a new page loads automatically when the user reaches the bottom of the page or a particular div. Currently, I have this code that loads a new page onclick. $("#about").click(function(){ ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...

What is the best method for testing routes implemented with the application router in NextJS? My go-to testing tool for this is vitest

Is it possible to test routes with vitest on Next.js version 14.1.0? I have been unable to find any information on this topic. I am looking for suggestions on how to implement these tests in my project, similar to the way I did with Jest and React Router ...

What is the method for breaking a statement within an if statement on Blogger when both the IF and ELSE conditions are met?

I'm making some adjustments to the labels on my blog to ensure that each post has at least two labels. The concept is that if a post has LABEL 1, it will load one script, otherwise it will load another. However, I've encountered a situation wher ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...