Modifying options within a <select> based on the selection made in another <select> element

Basically, I have 2 <select> elements. What I want is for the user to select an option in the first <select>, and then the options in the second <select> should change based on the selection made in the first one. The second <select> starts off empty, and when an option is chosen in the first <select>, it should dynamically add <options> to the second <select>.

HTML for the first select :

<select name="roof_width" onChange="getWidth(this.selectedIndex)" value="3" class="content_selectinput" id="select_width">
    <?php
        $i = 0;
        $x = 2;
        while(isset($dak_breedte[$i]))
        {
            if(isset($roof_width_index) && $roof_width_index == $i)
            {
                echo "<option value='$i' id='$i' selected='Selected'>" . $dak_breedte[$i] . " Meter </option>";
                $i++;
            }                   
            else
            {
                echo "<option value='$x'>" . $dak_breedte[$i]. " Meter</option>";
                $i++;
            }
        }
    ?>
</select>

HTML for the second select :

<select name="NokBreedte" onClick="ridgeCheck()" value="3" class="content_selectinput" id="select_ridge" >
</select>

JavaScript :

function getWidth(index)
{
    ridge_min = index - 10;
    ridge_max = index + 10
    ridge_select = document.getElementById("select_ridge");
    for(i = 0; i <= 99; i++)
    {
        if(i < ridge_min || i > ridge_max)
        {
            ridge_select.add(ridge_values[i]);
        }
    }
}

The text values for the second <select> are stored in an array. I've searched online and attempted using jQuery, but so far nothing has worked.

To clarify, what I'm looking for is:

When a user selects an option in the first <select>, the options in the second <select> should update instantly.

Answer №1

for those utilizing jQuery, it is recommended to replace the existing function with this one:

function getWidth(){
    var index = $('#select_width').val();
    ridge_min = index - 10;
    ridge_max = index + 10

    var options = '';


    for(i = 0; i <= 99; i++)
    {
        if(i > ridge_min || i < ridge_max)
        {
            options += "<option>" + ridge_values[i] + "</option>";
        }
     }

     $('#select_ridge').html(options);
}

Additionally, update

getWidth(this.selectedIndex)

to

getWidth()

Corrected Note:

Apologies for the confusion, but there was an error in the condition used.

if(i < ridge_min || i > ridge_max)

The correct form should be:

if(i > ridge_min || i < ridge_max)

Answer №2

First, ensure to remove all previous values (this code should be included in the onChange function)

//Clear the options in the HTML Select DropdownList
$('#select_ridge option').empty();

});

Next, add the new values

var listvalues = new Array();    
listvalues[0] = { Text: "value1", Value: "1" };
listvalues[1] = { Text: "value2", Value: "2" };    
listvalues[2] = { Text: "value3", Value: "3" };    

$.each(listvalues, function (index) {            
    $("#select_ridge").append(GetOption(listvalues[index].Text, listvalues[index].Value));        
});    

function GetOption(text, value) {        
    return "<option value='" + value + "'>" + text + "</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

`How to Customize Page Titles and Add Content in WooCommerce`

Currently, I am facing a challenge in adding content after the page title and changing the style of the page where all products are displayed in WooCommerce. Unfortunately, I am unsure about the location of the file that needs to be copied to my custom t ...

JSON containing attributes represented by Unicode characters

During the development of my web application, I am interested in utilizing JSON objects with Unicode attributes as shown below: a = { ονομα:"hello" } Subsequently, I would like to access it in this manner: a.ονομα Alternatively, exploring lo ...

arranging data in various categories with React.js

Can anyone figure out why this code is struggling to properly sort based on columns? sort(key){ this.setState({ [`toggle-${key}`]: !this.state[`toggle-${key}`], data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => ...

Error: The id provided does not contain information for the 'component' property

Looking to dynamically render different components based on ID in my React app. Currently using a switch case method, but now aiming to customize the header based on the component being rendered. The steps object in App.js is structured like this: ** Here ...

Is there a way to dynamically incorporate HTML tags (such as <button>) into the content of a Popover in Bootstrap using JavaScript?

I am currently utilizing Bootstrap-Popover and I would like to include a button inside the popover. Previously, this was functioning correctly but now it seems to have stopped working. <button type="button" class="btn btn-primary mx-2&quo ...

I struggle to format a classic HTML form dropdown menu that is populated using JavaScript

Hey everyone, I'm having an issue with styling a drop down menu that is populated by JavaScript. I've tried different things but nothing seems to be working. Any suggestions on how I can style the elements in the drop down? <form action="" me ...

Using video instead of static slides in HTML5

I am interested in adding a video background with text overlay on my website, similar to what can be seen here: Although I understand it involves CSS, I am struggling to achieve the desired effect. Here is the code snippet I have been using: video#bgvid ...

What is the reason that adding bottom padding and margins is ineffective in creating vertical space between these links?

I am struggling with aligning links vertically in a div. Currently, I am using <br> tags to stack them on top of each other because I couldn't find a way to add vertical spacing with CSS. I attempted to add bottom margin and padding to the &apos ...

Error: JSON parsing error due to unexpected token C at the beginning of the string

When using ajax and json formatting, I am encountering this message. In PHP, the code array("message" => "Success", "data" => $data) is displayed successfully. However, it is not able to callback to ajax. How can I resolve this issue without deleting ...

What is the method to retrieve the selected value from a drop-down menu that is connected to JSON keys?

I am just starting to learn AngularJS and I need help with binding column names (keys from key-value pairs) to a select list. I want to be able to retrieve the key name when the selection in the select list is changed. The select list displays: name, snip ...

Struggling to align my Navbar items in one clean line, they seem to pile up and remain fixed on the left side. Utilizing ReactJS and MUi5

I'm struggling with aligning my Navbar items (NavLink) horizontally in one line instead of being stuck on the right side and stacked on top of each other. Can someone help me fix this issue? Here's the code snippet: import React from "react& ...

"An error has occurred in the file system, make sure to handle it when

I am encountering an issue with submitting a form using jQuery's ajaxSubmit() function. The problem arises when the file selected in the form is renamed, deleted, or made inaccessible before submission, leading to potential discrepancies in whether th ...

"Addressing the issue of white space between the status bar and header in Cordova

I have tried numerous solutions but I am still unable to remove the white space between the header and status bar, as shown in the attached image. https://i.sstatic.net/a9xTG.jpg My current setup involves using Intel XDK version 3987 with Cordova plugin ...

Instructions for adding a Key every time a user clicks the space Key within an Input field

I built a Movie Search Page with the OMDB API. My current issue is that the API returns an error when searching for a movie with more than one word because the API URL requires a + key between each word. I am looking for a way to automatically add the + ke ...

The lightbox2 image gallery is completely nonfunctional

I tried following Lokesh Dhakar's step-by-step guide on how to create a slideshow image gallery, which can be found at . Unfortunately, I am still facing issues with it as instead of functioning as a gallery, it simply opens the images like basic link ...

AngularJS controller failing to deliver output

Just diving into the world of AngularJS, I've recently launched a new application but it seems like there's a crucial element missing when it comes to controllers. <!doctype html> <html lang="en> <head> <meta charset ...

Error: The "toString" property of an undefined variable cannot be read in uploadify

I'm having trouble with uploadify and trying to debug the issue. When attempting to use uploadify in Chrome, I encounter the following error: Uncaught TypeError: Cannot read property 'toString' of undefined Below is my html code: <li ...

How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this: { "options":[ { "optionId":"5ebbe0f56b197f36fc472168" }, { "optionId":"5ebbe1aa6b197f36fc47216e" } ] } The goal is to filter the data in a way that ...

Adjust the color of the text within a div element when hovering over and moving the mouse away

Is there a way to change the text color on mouse hover and mouse out, even with multiple nested div elements? I'm having trouble getting it to work, so any help would be appreciated. <div class="u860" id="u860" style="top: 0px;"> <div id ...

Unexpected outcome when applying texture to Collada mesh in Three.js

After following the Three.js ColladaLoader example, I exported a Cinema4D soda can model (made up of 4 meshes) to a .dae file. I am specifically trying to add a texture to the body of the can. In Cinema4D, I created a texture based on a UV map of the mesh ...