Question

I want to update one combobox by changing the second combobox. for example: I have this response (string):

var response = [{
    "A": "a2",
    "B": "b2",
    "C": "c2"
},
{
    "A": "a3",
    "B": "b3",
    "C": "c3"
},
{
    "A": "a3",
    "B": "b331",
    "C": "c33"
},
{
    "A": "a3",
    "B": "b33221",
    "C": "c3"
},
{
    "A": "a4",
    "B": "b4",
    "C": "c4"
},
{
    "A": "a2",
    "B": "b221",
    "C": "c222"
}];

and I want that in "myDropDownA" will be "a2, a3, a4". and for example: if I choose "a3" in "myDropDownA", than in "myDropDownB" will appear only: "b3, b331, b33221" (because they only refer to a3). and I don't want repeated of "A" objects.

var myDropDownA = $("#myDropDownA");
$.each(response, function (index, obj) {
    //alert(index + ": " + obj.A);
    myDropDownA.append($("<option />").val(obj.A).text(obj.A));
});

    var myDropDownB = $("#myDropDownB");
    $.each(response, function (index, obj) {
        //alert(index + ": " + obj.B);
        myDropDownB.append($("<option />").val(obj.B).text(obj.B));
});

what do I need to change (or to add) to make it work as above?

Was it helpful?

Solution

What you're missing is attaching an eventhandler to the change event of dropdown A repopulating dropdown B with relevant values.

var response = [
    { "A": "a2", "B": "b2", "C": "c2" },
    { "A": "a3", "B": "b3", "C": "c3" },
    { "A": "a3", "B": "b331", "C": "c33" },
    { "A": "a3", "B": "b33221", "C": "c3" },
    { "A": "a4", "B": "b4", "C": "c4" },
    { "A": "a2", "B": "b221", "C": "c222"}
];

var uniqueByProperty = function(arr, prop) {
    var seen = {};
    return arr.filter(function(elem) {
        var val = elem[prop];
        return (seen[val] === 1) ? 0 : seen[val] = 1;
    })
}

var aList = uniqueByProperty(response, "A");
var myDropDownA = $("#myDropDownA");
var myDropDownB = $("#myDropDownB");

// Populate dropdown A
$.each(aList, function(index, obj) {
    myDropDownA.append($("<option />").val(obj.A).text(obj.A));
});

// Attach event handler for dropdown A
myDropDownA.on('change', function(){
    var ddl = $(this);

    // Get related objects
    var bList = response.filter(function(elem) {
        return (elem.A === ddl.val());
    });

    // Populate dropdown B
    myDropDownB.empty();
    $.each(bList, function(index, obj) {
        myDropDownB.append($("<option />").val(obj.B).text(obj.B));
    });
});

// Trigger population of dropdown B
myDropDownA.change();

See this jsfiddle for a working demonstration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top