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?
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.
$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").
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.
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> 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With