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?
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!'))
}
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");
}
}
http://jsfiddle.net/zpdEp/
Try
var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With