I want to invoke javascript function when value in the dropdown list changes. I dont want to hardcode dropdown list id .
Hence not using document.getElementById
My Code:
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
function jsFunction(value)
{
alert(value);
}
This is giving error ReferenceError: jsFunction is not defined
Fiddle : http://jsfiddle.net/6uyz4b8x/1/
Best procedure for cases like this would be, to add a common class to all the dropdowns for which you want to call the function on change. For ex: add 'trigger-change' class for all your required dropdowns. Then below bind event should work perfect for you. $('form select.
The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
The HTML Select DropDownList has been assigned a jQuery OnChange event handler. When an item is selected in the HTML Select DropDownList, the jQuery OnChange event handler is executed within which the Text and Value of the selected item is fetched and displayed in JavaScript alert message box.
Your code is working just fine, you have to declare javscript method before DOM ready.
I don't know why do you need this onmousedown
event here, but what you have to do is put your function above actual usage. Look at the snipplet below:
<script type="text/javascript">
function jsFunction(value)
{
alert(value);
}
</script>
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
using jQuery
$("#ddl").change(function () {
alert($(this).val());
});
jsFiddle
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