Get Selected value from dropdown using JavaScript
230,263
Solution 1
Maybe it's the comma in your if
condition.
function answers() {
var answer=document.getElementById("mySelect");
if(answer[answer.selectedIndex].value == "To measure time.") {
alert("That's correct!");
}
}
You can also write it like this.
function answers(){
document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}
Solution 2
Try
var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
Solution 3
The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );
You should also try and clean up your if statement by declaring a variable for the answer separately.
function answers() {
var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;
if(answer == "To measure time"){
alert("Thats correct");
}
}
Solution 4
Working jsbin: http://jsbin.com/ANAYeDU/4/edit
Main bit:
function answers()
{
var element = document.getElementById("mySelect");
var elementValue = element.value;
if(elementValue == "To measure time"){
alert("Thats correct");
}
}
Related videos on Youtube
Author by
craig
Updated on July 09, 2022Comments
-
craig almost 2 years
I have the following HTML
<form> <div class="answer1wrap"> <select id="mySelect"> <option value="void">Choose your answer</option> <option value="To measure time">To measure time</option> <option value="To measure distance">To measure distance</option> <option value="To measure volume">To measure volume</option> </select> </div> </form> <button class="btn btn-default" id="checkbtn" onclick="answers();" type="button"><span class="glyphicon glyphicon-check"></span> Check answers</button>
I also have the javascript
function answers() { var selectedanswer=document.getElementById("mySelect").selectedIndex; if (document.getElementsByTagName("option")[selectedanswer].value=="To measure time");{ alert("Thats correct"); } }
I was hoping that when the button is pressed, it would check to see if the 'to measure time' option was selected and alert me ONLY if that was selected. However no matter which option has been selected it always shows the alert.
Any ideas?
-
Admin almost 8 yearsRefer this article: javascriptstutorial.com/blog/…
-