0

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?

10
  • 1
    I copied your code into a fiddle, jsfiddle.net/wqq4pmte and it alerts the value of the selected item in your select element. What were you expecting to happen? Commented Oct 2, 2014 at 11:43
  • This is really strange, I tried it in JS Bin and nothing would happen. The only difference was that I did not split it between the HTML and JS windows but embeded the JS code in the HTML. I'll check it out in Webstorm when I get home, thanks! Commented Oct 2, 2014 at 11:49
  • I have to double-post for visibility: In your JS fiddle the code only alerts the first selected item, why's that? Commented Oct 2, 2014 at 11:54
  • It's showing the first value because both functions are being called when the page is loaded, and therefore the first value is alerted. I'm guessing you want to alert the value when the select element is changed? Commented Oct 2, 2014 at 12:15
  • Yes, that's exactly what I would like the code to do:) Commented Oct 2, 2014 at 12:25

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thank you, I'm not acquainted with jquery yet, but I'll have a look at it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.