1

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
  • Are you using a JavaScript framework like jQuery? Commented Oct 19, 2010 at 17:36

4 Answers 4

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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 quirksmode.org/dom/w3c_core.html)
Should work fine for this example though (although adding an id to the select would be preferable, as everyone seems to agree)
1

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

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.