tags:

views:

50

answers:

4

How can I alert the value selected by user from a select drop down box in Javascript. In this example I want to store the value inside a variable and alert it to the user.

<script type="text/javascript">

function processmyform() {

    var chosenAnimal = // what goes here

    alert(chosenAnimal);

}
</script>

<form action="">
    <select name="animal" class="favAnimal">
        <option value="dog">Dog</option>
        <option value="cat">Cat</option>
        <option value="bird">Bird</option>
    </select>
    <a href="#" onclick="processmyform()" />
</form>
+1  A: 

I'd generally put an id on the select, like id="animal"

Then you could do:

var animal = document.getElementById("animal");
var animalValue = animal.options[animal.selectedIndex].value;
alert(animalValue);
Tim Goodman
+1  A: 

I would set an id on your select-tag:

<select id="animal" name="animal" class="favAnimal">

Javascript:

var chosenAnimal = document.getElementById("animal").value;
alert(chosenAnimal);
Onkelborg
+1  A: 

Use selectedIndex

<form id="yourForm" action="#">
    <select id="animal" name="animal" class="favAnimal">
        <option value="dog">Dog</option>
        <option value="cat">Cat</option>
        <option value="bird">Bird</option>
    </select>
    <input type="submit" value="Submit" />
</form>

window.onload = function(){
    var selectElement = document.getElementById('animal');

    document.getElementById('yourForm').onsubmit = function(){
        var index = selectElement.selectedIndex;
        alert(selectElement.options[index].value);
        alert(selectElement.options[index].text);
        alert(index);
        return false;
    };
};
Harmen
+1  A: 

First off, it would be easier if your select box had an id. Then you could use getElementById.

var animalSelectBox = document.getElementById('animal');
alert(animalSelectBox.options[animalSelectBox.selectedIndex].value);

Instead, here is how to do it using getElementsByName (notice this one is plural).

var arr = document.getElementsByName('animal'); //will be an array
alert(arr[0].options[arr[0].selectedIndex].value);
Gabriel McAdams
Be careful, though, getElementsByName has non-standard behavior in IE and Opera (gets elements that match name *or* id), and won't work on certain elements in IE. (See http://www.quirksmode.org/dom/w3c_core.html)
Tim Goodman
Should work fine for this example though (although adding an id to the select would be preferable, as everyone seems to agree)
Tim Goodman