Sam
Sam

Reputation: 25

How to get the value of a select drop down in javascript?

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>

Upvotes: 1

Views: 23424

Answers (4)

Harmen
Harmen

Reputation: 22438

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;
    };
};

Upvotes: 1

Gabriel McAdams
Gabriel McAdams

Reputation: 58253

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);

Upvotes: 4

Onkelborg
Onkelborg

Reputation: 3987

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);

Upvotes: 1

Tim Goodman
Tim Goodman

Reputation: 23976

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);

Upvotes: 1

Related Questions