0

I have an HTML element like this:

<td>
    <select>
        <option value="Polygon 47">Polygon 47</option>
        <option value="Polygon 49">Polygon 49</option>
    </select>
</td>

How can I access the currently selected value with JavaScript?

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
ustroetz
  • 5,802
  • 16
  • 47
  • 74
  • when do you want to access? on option change or on button click? – Bharadwaj Mar 18 '14 at 13:16
  • When I call a different function (is called when I hit the a button), I want to select the currently set value. – ustroetz Mar 18 '14 at 13:17
  • There is a lot of work for this without having id for the dropdown. Find one parent element with `id` property, and then find the containing elements by accessing `childNodes` property of that element in `javascript`. You need to do this until you get the required element. **OR** use `jquery` which would be lot easier that javascript in this case. – Bharadwaj Mar 18 '14 at 13:33

3 Answers3

0

I solved it by using getElementsByTagName.

        var e = cell.getElementsByTagName("select")[0];
        var myValue = e.options[e.selectedIndex].value);
ustroetz
  • 5,802
  • 16
  • 47
  • 74
-1

Solution:

<select id="shape">
<option value="Polygon 47">Polygon 47</option>
<option value="Polygon 49">Polygon 49</option>
</select>

<script type="text/javascript">
$(document).ready(function () {

    $('#shape').change(function(){
    var shapeId = document.getElementById("shape");
    var shapeChosen = shapeId.options[shapeId.selectedIndex].value;
    //Now use 'shapeChosen' wherever you want. 'shapeChosen' will give you the selected item.
   });
});
</script>
Aniruddha Pondhe
  • 1,830
  • 3
  • 17
  • 30
-1
<select id="test">
<option value="Polygon 47">Polygon 47</option>
<option value="Polygon 49">Polygon 49</option>
</select>

$("#test").change(function() {alert($("#test option:selected").val())})