Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect when a user clicks on an option in a drop down menu (select tag)

I have a select and I want to run a different javascript function depending on what they select when they click it in the menu. My googling has been unfruitful, can anyone direct me to the correct property? (for example, I know that onclick works well with buttons). Thanks in advance for any help!

EDIT: onchange doesn't work in my code.

<head>
    <script>
        function goToDelete(){
            document.write("Death to this webpage!")
        }
    </script>
</head>
<form id="checkboxes" method="post" action="someurl">
    <tr>
        <td><input type="checkbox" name="Selection"/></td>
        <td>Some more rows to the table here</td>
    </tr>
    <select name="action">
        <option value="Delete" onchange="goToDelete()">Delete</option>
    </select>
like image 941
avorum Avatar asked Jun 17 '13 19:06

avorum


2 Answers

I'd suggest using the change/onchange event, though this only fires if the user selects an option that wasn't previously selected (hence the name).

A simple demonstration of how you can use change (tested in Chrome 27/Windows XP):

var select = document.getElementById('demo');

function logValue() {
    switch (this.value) {
        case '1':
            console.log('option 1 selected');
            break;
        case '2':
            alert('option 2 selected');
            break;
        case '3':
            confirm('You chose option 3, didn\'t you?');
            break;
    }
}

select.addEventListener('change', logValue, false);

JS Fiddle demo.

It's important to note that the change/onchange event must be bound to the select element, not the option elements. The options themselves don't change, selecting them triggers the change.

References:

  • change.
like image 101
David Thomas Avatar answered Nov 07 '22 10:11

David Thomas


function SelectedValue(sel) {
    var value = sel.options[sel.selectedIndex].value;  
    //Do something depending on value
}
<select id="myid" onchange="SelectedValue(this)">
    <option value="">Select options</option>
    <option value="Value1">Text1</option>
    <option value="Value2">Text2</option>
    <option value="Value3">Text3</option>
</select>
like image 28
Ani Avatar answered Nov 07 '22 10:11

Ani