Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the selected item's value of a html dropdown menu in a javascript function

I have a form in html that contains a drop down menu like so

<form name= "gadget_selector">
    <select name= "gadget">
        <option value = 0> Something </option>
        <option value = 1> Something else </option>
        //etc..
    </select> 
</form> 

And I want to access the value of the selected option in a javascript function like so

function someFunction(){

    //var option = value of selected menu option
}

How would I do this?

like image 545
Zack Avatar asked Jan 07 '12 06:01

Zack


People also ask

How do I get the value of the selected dropdown menu item?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list.

How do I get the selected value and current selected text of a dropdown box using jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How do you check if a dropdown is selected in JavaScript?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} . The tagName property returns the tag name of the element on which it was accessed.


1 Answers

var option = document.getElementById('gadget').value;

Set gadget as the id for the select as well, like this:

<select id="gadget" name="gadget">
        <option value = 0> Something </option>
        <option value = 1> Something else </option>
        //etc..
    </select> 
like image 180
xbonez Avatar answered Sep 28 '22 04:09

xbonez