How to get the value of a select drop down in javascript? – Education Career Blog

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>

,

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.optionsanimalSelectBox.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(arr0.optionsarr0.selectedIndex.value);

,

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

Then you could do:

var animal = document.getElementById("animal");
var animalValue = animal.optionsanimal.selectedIndex.value;
alert(animalValue);

,

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

,

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.optionsindex.value);
        alert(selectElement.optionsindex.text);
        alert(index);
        return false;
    };
};

Leave a Comment