user5739619 user5739619 - 2 years ago 77
Javascript Question

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

This is what I've constructed so far:

I want to display a value in the

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

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

If the 1st choice is
and the 2nd choice is
, then I want the
textbox to display
. And vice-versa, so if the 1st choice is
and the 2nd choice is
then I want
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
for both menus, then I want there to be no output

How can I program this?

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

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

Answer Source

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 = $ (index, el) {
        return Number($(el).val());

    $output.val(values[key] || '');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download