I’m trying to get two values from different select elements and access those elements outside a function.
function firstValue(){ var e = document.getElementById("val-selec"); var strUser = e.options[e.selectedIndex].text; return strUser; } function secondValue(){ var e1 = document.getElementById("val-selec1"); var strUser1 = e.options[e.selectedIndex].text; return strUser1; } if(firstValue() == "val1" && secondValue() == "val2"){ //do something }
when I log my function it just returns the first value it does not change when you select another option. What would be a way I can compare values and to a certain thing
https://jsfiddle.net/v50wdnL1/1/ I included a jsfiddle
Advertisement
Answer
Not quite sure why the #onchange
events are calling function that only return values and dont do any meaningful operations. Instead make them both call a compare function and in that compare function call your other function which return the values. Example below:
HTML:
<select name="val-select" id="val-selec" onchange="compare();"> <option value="" disabled selected>Select your option</option> <option value="val1">val1</option> <option value="val2">val2</option> <option value="val3">val3</option> <option value="val4">val4</option> </select> <br> <select name="val-select1" id="val-selec1" onchange="compare();"> <option value="" disabled selected>Select your option</option> <option value="val1">val1</option> <option value="val2">val2</option> <option value="val3">val3</option> <option value="val4">val4</option> </select>
JavaScript:
function firstValue(){ var e = document.getElementById("val-selec"); return e.value; } function secondValue(){ var e1 = document.getElementById("val-selec1"); return e1.value } function compare(){ var value1 = firstValue(); var value2 = secondValue(); console.log(value1 === value2); }