Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Selected value from dropdown using JavaScript [duplicate]

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?

like image 296
craig Avatar asked Sep 17 '13 10:09

craig


3 Answers

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!'))
}
like image 63
cocco Avatar answered Nov 08 '22 10:11

cocco


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/

like image 5
Wez Avatar answered Nov 08 '22 12:11

Wez


Try

var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
like image 5
Derk Arts Avatar answered Nov 08 '22 11:11

Derk Arts