How to implement a dynamic combo box selection system

I am implementing the system these days, I want to implement the combo box selection process, but I don’t know how to implement it, so ask guys, would you prefer?

my scenario is, let’s say, we have two lists for selecting lists with a list, on the left and on the right, one of them is one, and the right is a child of the left.

when I select an item from the left combo box, the contents of the right combo box should be changed according to the choice of the left,

Example: think about mobile phones if I choose a brand

Nokia

in the right combo box, the right combo box should be changed to

C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73 

how wise. please help me implement such a scenario! any links to tutorials, sample code for understanding the script is better!

Regards, Rangana

+3
3

, reset .

HTML:

<select id="brand"> 
    <option value="">- select -</option> 
    <option value="nokia">Nokia</option> 
    <option value="apple">Apple</option> 
</select> 

<select id="type"></select> 

JavaScript ():

var selectBrand = $("#brand");
var selectType = $("#type");

var optionsList = {
    nokia: [
        "C6-01",
        "E7-00"
    ],
    apple: [
        "iPhone 3",
        "iPhone 3G",
        "iPhone 4"
    ]
};

selectBrand.change(function() {
    var brand = selectBrand.val();
    var options = optionsList[brand];
    var html;

    if (options) {
        html = '<option value="">- select -</option>';
        $.each(options, function(index, value) {
            html += '<option value="' + value + '">' + value + '</option>';
        });
    } else {
        html = '<option value="">Select a brand</option>';
    }
    selectType.html(html);
}).change();

See http://www.jsfiddle.net/TJJ8f/

+3

, . -, , JSON , -, .

<?php

    // Do what you need to
    $modelsArray = getModelsForBrand($_REQUEST['brand']);
    echo json_encode($modelsArray);
?>

json_encode, JSON , , . , .

jQuery :

$("#brandCombo").change(function(){
    var chosenBrand = $(this).val(); // Get the value

    $.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){

        // Successful return from your PHP file

        $("#modelCombo").empty();

        // For each item returned, add it to your models combo box
        $.each(request, function(i,item){
            $("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
        });
    });
});

brandCombo - , modelCombo - , . brandCombo , PHP JSON. modelCombo.

, , , , (/ ) AJAX ( ).

, dyve, , JavaScript. , PHP json_encode ( ).

+2

Source: https://habr.com/ru/post/1780206/


All Articles