Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Dropdown, JQuery, Not Submitting form with Value

I have the following code, which creates a dynamic dropdown (Text Color) based on the selection of another dropdown (Background Color)

It works as expected, and populates the Text Color dropdown perfectly.

However, when I submit my form, the value for textC is blank everytime. If I create a simple select for Text Color, my form submits fine, and all variables are available on the next page via POST.

Any thoughts to why the the textC value is always blank with this code?

var black = [
{display: "Gray", value: "gray" }, 
{display: "Warm Red", value: "red" }, 
{display: "White", value: "white" }];

var white = [
{display: "Black", value: "black" }, 
{display: "Gray", value: "gray" }, 
{display: "Warm Red", value: "red" }];

var gray = [
{display: "Black", value: "black" }, 
{display: "Warm Red", value: "red" }, 
{display: "White", value: "white" }];

$("#parent_selection").change(function() {
    var parent = $(this).val(); //get option value from parent 
    
    switch(parent){ //using switch compare selected option and populate child
          case 'black':
            list(black);
            break;
          case 'white':
            list(white);
            break;              
          case 'gray':
            list(gray);
            break;  
          default: //default child option is blank
            $("#textC").html('');  
            break;
       }
});

//function to populate child select box
function list(array_list)
    {
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options 
        $("#textC").append("<option value=''+array_list[i].value+''>"+array_list[i].display+"</option>");
    });
}
<p><b>Background Color ?</b><br>
<select name="theme" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="black">Black</option>
    <option value="white">White</option>
    <option value="gray">Gray</option>
</select>

<p><b>Text Color?</b><br>			
<select name="textC" id="textC">
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
like image 603
Vacek Avatar asked Sep 09 '26 03:09

Vacek


1 Answers

Can you try this instead:

//function to populate child select box
function list(array_list)
{
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options 
        $('<option>').val(array_list[i].value).text(array_list[i].display).appendTo('#textC');
    });
}

JSFiddle: https://jsfiddle.net/Anokrize/t1w1k463/

like image 126
Tom el Safadi Avatar answered Sep 11 '26 17:09

Tom el Safadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!