giacomotb
giacomotb

Reputation: 607

Retrieve combobox value in javascript

This is my little program, what could i do for take the combobox value??

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <link rel="stylesheet" type="text/css" href="NewFile.css">
  <title>Insert title here</title>
  <script type="text/javascript">
    function calcola(){
        var op = String(document.getElementById("combo").value);
        alert(op);
    }   
  </script>
</head>
<body>
  <div class="in">
    Inserire il primo numero: 
    <input type="text" id="primo">
    <br>
    Inserire il secondo numero:
    <input type="text" id="secondo">
  </div>
  <div class="in">
    <select id="combo">
      <option selected="selected">*</option>
      <option>/</option>
      <option>+</option>
      <option>-</option>
    </select>
  </div>
  <div>
    <input type="button" name="bottone" value="Premi" onclick="calcola();">
  </div>

</body>
</html>

This program should be a calculator, but I omitted most of code because it's necessary to know the operator befor doing calculations.

Upvotes: 0

Views: 17019

Answers (2)

Harsha Venkataramu
Harsha Venkataramu

Reputation: 2904

Try this

function calcola()
{
    var element = document.getElementById("combo");
    var op = element.options[element.selectedIndex].value;
    alert(op);
} 

Upvotes: 4

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12042

Inside your function:

function calcola(){
    var elt = document.getElementById("combo"),
        op = elt.options[elt.selectedIndex].text;
    alert(op);
}

Buon lavoro collega italiano ;)

Upvotes: 0

Related Questions