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>
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 option
s themselves don't change, selecting them triggers the change.
References:
change
.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>
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