Home > database >  Get values from two select element and compare in another function
Get values from two select element and compare in another function

Time:12-29

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

CodePudding user response:

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);
}

CodePudding user response:

ok so, I think your code fails because you have a typo (depending where you want to put that if(condition){do_something()}, you are trying to access e when you should access e1 in the function secondValue()

I think you can get away without declaring those functions for the values like so:

function my_action(){
  let firstValue  = document.querySelector('#val-selec').value;
  let secondValue = document.querySelector('#val-selec1').value;
  if(firstValue == "val1" && secondValue == "val2"){
  //do something

  }
}

and then execute that func when u change the select:

<select name="val-select" id="val-selec" onchange="my_action();">

I hope is useful

  • Related