user4096694
user4096694

Reputation:

Get value from dropdown and pass it to another function (JS)

can you tell me what's wrong with my code?

I've got this dropdown list:

<select name="mySelect" id="mySelect" onchange="getSelectedValue();">  
<option value="1">Text 1</option>  
<option value="2">Text 2</option>  

And the following script:

function getSelectedValue() {  
var index = document.getElementById('mySelect').selectedIndex;  
var index = document.getElementById('mySelect').value;  
return index;    
}  
function passValue(x){
var a = x;
alert(a);
}    
passValue(getSelectedValue());

The getSelectedValue function works fine, but when I try to pass the value it returns to the passValue function nothing happens. What am I doing wrong here?

Upvotes: 0

Views: 2998

Answers (2)

T J
T J

Reputation: 43156

You can add a change event listener and call passValue function as follows:

var select = document.getElementById('mySelect');

select.addEventListener("change",function() {
  passValue(this.value);
});

function passValue(x) {
  var a = x;
  console.log(a);
}
<select name="mySelect" id="mySelect" >
  <option value="1">Text 1</option>
  <option value="2">Text 2</option>
</select>

Upvotes: 2

Harutyun Abgaryan
Harutyun Abgaryan

Reputation: 2023

Try this

function getSelectedValue() {  
var index = document.getElementById('mySelect').selectedIndex;  
var index = document.getElementById('mySelect').value;  
return index;    
}  
function passValue(x){
var a = x();
alert(a);
}

jQuery('#mySelect').change(function(){
    passValue(getSelectedValue)
})

Upvotes: 0

Related Questions