Employing IF conditions within a form to refine options

I am looking to streamline the options in my form based on the car and transmission selected. I have set up the form, but I am struggling with the JavaScript code. I need help figuring out how to only display certain color options when Car 1 is chosen along with Automatic transmission (for example, only Black and Blue). As a beginner in coding, any guidance would be greatly appreciated.

Thank you

HTML

<script src="Script\configurator.js" type="text/javascript"></script>
<form name="CarConfigurator">
   <select name="Car_make" onchange="Transmission(this.value);">
      <option value="" selected="selected">None</option>
      <option value="1">Audi RS6</option>
      <option value="2">BMW M4</option>
      <option value="3">Mercedes C63 AMG</option>
   </select>
   <br>
   <br>
   <select name="A_M">
      <option value="" selected="selected">None</option>
      <option value="1">Automatic</option>
      <option value="2">Manual</option>
   </select>
   <br>
   <br>
   <select name="Color">
      <option value="" selected="selected">None</option>
      <option value="1">Black</option>
      <option value="2">Blue</option>
      <option value="3">Red</option>
      <option value="4">White</option>
      <option value="5">Green</option>
   </select>
</form>

Javascript

function Transmission(Car) {
    var make = document.CarConfigurator.A_M;
    make.options.length = 0;
    if (Car == "1") {
        make.options[make.options.length] = new Option('Automatic','1');
        make.options[make.options.length] = new Option ('Manual','2');
    }
    if (Car =="2" ) {
        make.options[make.options.length] = new Option('Manual','2');
    }
    if (Car == "3") {
        make.options[make.options.length] = new Option('Automatic','3');
    }
}

Answer №1

Is this what you desire:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form name="CarConfigurator">
        <select name="Car_make" onchange="Transmission();">
            <option value=" " selected="selected">None</option>
            <option value="1">Audi RS6</option>
            <option value="2">BMW M4</option>
            <option value="3">Mercedes C63 AMG</option>
        </select>
        <br>
        <br>
        <select name="A_M" onchange="Transmission();">
            <option value="" selected="selected">None</option>
            <option value="1" selected="selected">Automatic</option>
            <option value="2" selected="selected">Manual</option>
        </select>
        <br>
        <br>
        <select name="Color" onchange="ChoicesMade();">
            <option value="" selected="selected">None</option>
            <option value="1">Black</option>
            <option value="2">Blue</option>
            <option value="3">Red</option>
            <option value="4">White</option>
            <option value="5">Green</option>
        </select>
        <div id="imageContainer" style="display: none;"><img src="http://buyersguide.caranddriver.com/media/assets/submodel/6873.jpg" /></div>
    </form>
    <script type="text/javascript">
        function Transmission() {
            var Car = document.CarConfigurator.Car_make.value;
            var make = document.CarConfigurator.A_M.value;
            var color = document.CarConfigurator.Color;
            color.options.length = 0;
            if (Car == "1" && make == '1') {
                color.options.add(new Option('Black', '1'));
                color.options.add(new Option('Blue', '2'));
            }
            else if(Car == '2' && make == '1')
            {
                color.options.add(new Option('Red', '3'));
                color.options.add(new Option('White', '4'));
            }
            ChoicesMade();
        }

        function ChoicesMade()
        {
            var form = document.CarConfigurator;
            var car = form.Car_make.value;
            var make = form.A_M.value;
            var color = form.Color.value;
            if(car != ' ' && make != '' && color != '')
            {
                var imageContainer = document.querySelector('#imageContainer');
                imageContainer.style.display = 'block';
            }
        }
    </script>
</body>
</html>

Answer №2

In JavaScript, you have the ability to utilize objects and iterate through each array within an object to modify options. Here's an example:

var vehicles = {
"Audi_RS6":{
    "name":"Audi RS6",
    "Automatic":["color_1","color_2"],
    "Manual":["color_1","color_2"]
    },
"BMW_M4":{
    "name":"BMW M4",
    "Manual":["color_1","color_2"]
    },
"Mercedes_C63_AMG":{
    "name":"Mercedes C63 AMG",
    "Automatic":["color_1","color_2"]
    }
};

You can access values like this:

var result = vehicles.Audi_RS6.Manual[1];

Answer №3

Hey Duncher, check out this code that fulfills your requirements

<!DOCTYPE html>
    <html><head>
    <title></title>
</head>

<body>
    <form name="CarConfigurator">
        <select id="car" name="Car_make">
            <option value="" selected="selected">Which car?</option>
            <option value="car1">Audi RS6</option>
            <option value="car2">BMW M4</option>
            <option value="car3">Mercedes C63 AMG</option>
            </select>
        <br>
        <br>
        <select id="trans" name="A_M">
            <option value="" selected="selected">What trans?</option>
            <option value="auto">Automatic</option>
            <option value="man">Manual</option>
            </select>
        <br>
        <br>
        <select id="color" name="Color">
            <option value="" selected="selected">What Color?</option>
             <option value="black">Black</option>
             <option value="blue">Blue</option>
             <option value="red">Red</option>
             <option value="white">White</option>
             <option value="green">Green</option>
             </select>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
    </script>
    <script src="configurator.js"></script>
</body>
</html>

Additionally, included is JavaScript:

$("#car").change(function () {
    transmission();
});

$("#trans").change(function () {
    transmission();
});

function transmission() {
    if ($("#car").val() == "car1" && $("#trans").val() == "auto") {
        $("option[value$='red']").hide();
        $("option[value$='white']").hide();
        $("option[value$='green']").hide();
    } else {
        $("option[value$='red']").show();
        $("option[value$='white']").show();
        $("option[value$='green']").show();
    }
}

To fully customize for other car and transmission combinations, you may need to add more if-else statements within the transmission() method. This script utilizes jQuery.

Take a look at the screen shot

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

Prerender is running independently of the dynamic page title and meta tags rendering process

As part of a POC, I was integrating prerender.io with an angular-node application for SEO purposes. My application can be found HERE. The good news is that all three links are being crawled successfully, as confirmed by receiving a 200 OK status for all li ...

Lose the scrollbar but still let me scroll using the mouse wheel or my finger on the fullscreen menu

I am currently working on a fullscreen menu design. However, when the menu appears, some elements are not visible unless I apply the overflow-y: scroll property to the menu. But I don't like the appearance of the additional scrollbar that comes with i ...

Issue with Jquery checkbox calculator constantly displaying Not a Number (NaN)

I'm facing an issue with jQuery. The Custom Wpform Checkbox Field is returning NaN. HTML <div class="wpforms-payment-total"> $ 85 </div> <input type="checkbox" name="myBox2" size="1 ...

Guide to positioning elements in CSS

I'm struggling to get all the elements to align in a single row. I've tried using display: inline-block, but it's not working as expected. I'm working with DataTables and I want the button images to be aligned with the page number box. ...

Unchecking a box becomes impossible in Rails and Ajax due to boolean constraints

Even though I've come across several similar questions, I'm still struggling to make mine work correctly. Here's what my code looks like... #app/views/tasks/index.html.erb <%- @tasks.each do |task| %> <div class="task-wrapper"> ...

Prevent a JavaScript file from resetting when a user refreshes the page

I'm currently developing a desktop application using node.js and electron. My task involves creating a JavaScript file that manages multiple processes, stores them in a dictionary, and ensures that the dictionary content is retained even without any r ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

Why isn't my CSS float behaving as I anticipated?

I'm currently working on a website and facing an issue. The CSS Float property is not behaving as expected. Here is my HTML Code: <div class="slider-menu"> <div class="slider-box"> <img src="agac.jpg"> & ...

What is the significance of the "component" prop within MUI components?

I am a beginner in React and HTML. Currently, I am using MUI and React to create my own website. I am currently attempting to add an "Upload button" that will allow me to select an image file when clicked. Below is the official implementation: <Button ...

Sass can be used to create custom color classes for Bootstrap 5.3 that offer

I am currently using a Bootstrap 5.3 theme and I would like to give users the option to change the main color theme from the default blue to something like purple or orange. My idea is to create additional CSS files named "orange-as-primary.css", "purple- ...

Resetting initial values with Velocity.js post-animation

After animating elements into view on a page, I want to defer further animation through CSS classes. However, Velocity keeps all animated properties in the style= tag, hindering CSS transitions. My solution involves resetting the CSS upon completion, but ...

The information from the textarea and select option is not getting through to the email

Despite following suggestions, I am still unable to figure out why my form is not functioning properly. The form I have collects various information such as name, email, phone number, a select option, and a message in a textarea input. I dynamically change ...

Dynamic placement of divs when new content is added to the page

Before we begin, I'll provide you with the complete HTML code of my webpage: <div align="center"> <img src="http://questers.x10.bz/Header.png" style="position: absolute; margin-left: -440px; box-shadow: 0px 3px 12px 2px #000;" class="rotate" ...

Clicking on the user will reveal a modal containing all of the user's detailed information

**I am trying to pass the correct user data to the modal ViewUser component, but it keeps displaying the same user regardless of which user I click on. How can I specify the specific user whose data should be shown? I am sending the user information as a ...

The landscape orientation media query does not adhere to the specified maximum width

I am currently working on creating a mobile landscape design for a website specifically tailored for iPhone SE and iPhone 12. In the process, I encountered an issue that caught my attention: Within two different breakpoints, I made adjustments to the top ...

Looking to implement client-side JavaScript validation prior to utilizing jQuery AJAX validation

I'm struggling to make sure that my validate(form) function runs "before" my ajax function. I would appreciate any suggestions on how to connect the two and ensure they run in sequence when the form is submitted. Thank you! <script type="text/ ...

Regular expression to detect a space that is escaped

Given a string: rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application\ Support/Sublime\ Text\ 3/Packages /Users/ken/Google\ Drive/__config-GD/ST3 Attempting to find a regex pattern that matches spaces, but ex ...

Switching back and forth between JQuery and CSS display changes

My challenge involves utilizing a JQuery file to present one question at a time in a quiz format. Upon clicking the submit button, the intention is to progress to the subsequent question. However, I have encountered an issue where the transition occurs mom ...

In the Sandbox, element.firstChild functions properly, but it does not work in the IDE

Encountered an issue that has me puzzled. To give you some context, I attempted to create a native draggable slider using React and positioned it in the center of the screen, specifically within my Codesandbox file. The code snippet I utilized is as follow ...

What is preventing the clickHandler from properly updating the state?

My goal is to dynamically change the background image based on the active button clicked. Although the clickHandler correctly identifies the button id, the state fails to update as expected. Can you help me spot what I may have missed? import React, { Com ...