user5739619 user5739619 - 3 months ago 11
Javascript Question

Display value depending on selected values from 2 Dropdown menus in Javascript?

This is what I've constructed so far: https://plnkr.co/edit/fnhKUhuTYjUTQgJLnZoT?p=preview

I want to display a value in the

input
textbox that depends on the user's 2 choices from the 2 dropdown menus. I want that value to come from the
values
array here:

var values = [1, 2, 0.1, 1, 3, .2, 2, 3,.3];


If the 1st choice is
1
and the 2nd choice is
2
, then I want the
input
textbox to display
0.1
. And vice-versa, so if the 1st choice is
2
and the 2nd choice is
1
then I want
0.1
to be the output.

And I want nothing to happen if the user chooses the same value for both menus. So if the user chooses
2
for both menus, then I want there to be no output

How can I program this?

EDIT: I should probably first convert the
values
array to a hashmap like this:

var values = [(1, 2): 0.1, (1, 3): .2, (2, 3): .3];

Answer

I hope you won't mind me using jQuery in my solution since you had it included in your Plunk.

var $selects = $('select');
var $output = $('#pred');

First I will create a map of input pairs to output values.

var values = {
    '1,2': 0.1,
    '1,3': 0.2,
    '2,3': 0.3
};

Next, I will listen for a change event on the select menus. In my change handler, I will map the values of the selects into an array of numbers. Next, by sorting and joining this array, I should end up with a stringed pair of numbers in ascending order and delimited by a comma; a key, just like the keys in my values object.

Finally, I will set the value of $output to the value of values at the resultant key. If values[key] is undefined, I will default to an empty string.

$selects.on('change', function () {
    var key = $selects.map(function (index, el) {
        return Number($(el).val());
    })
        .get()
        .sort()
        .join(',');

    $output.val(values[key] || '');
});