I need to call a javascript function when the dropdown list is changed.
How can I implement that in asp.net?
I need to call a javascript function when the dropdown list is changed.
How can I implement that in asp.net?
Use onchange event to excecute function whenever the dropdown list clicked.
<select id="mylist" onchange = "go()">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<script>
function go()
{
var x = document.getElementById("mylist").value;
console.log(x);
}
</script>
<asp:DropDownList runat="server" ID="DDList" onclick="alert(1)"></asp:DropDownList>
If you want to get function executed when element clicked, you can use above code to define a function that should be executed 'onclick'.
But it is better to use something like addEventListener, just search for cross-browser function (for instance, like addListener function here):
document.getElementById("<%=DDList.ClientID %>").addEventListener("click", fucntionToExecuteName, false)
Remember, than in this case you must take DDList.ClientID and use it as id of an element, because it will be different from ID you have set in your aspx code
But if you need some function to be executed when actual value is changed, you should use onchange event.
Add this script to your mark-up and be sure to also include a script reference to jquery:
$(document).ready(function()
{
$("#yourDropdownId").change(function(){
//Todo: write your javascript code here.
});
});
Make sure that the control with "yourDropdownId" as ID has the property: "ClientIDMode" set to static or the "all-knowing" ASP.NET engine will auto-generate an element name for the resulting html with parent element names appended to the control by default.
You can use an onchange event and call it from itself:
<asp:DropDownList ID="DropdownList" runat="server" onchange="javascript:MyFunction();" >
</asp:DropDownList>