Skip to content Skip to sidebar Skip to footer

How To Call A Javascript Function Using Asp.net Dropdown List

I need to call a javascript function when the dropdown list is changed. How can I implement that in asp.net?

Solution 1:

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>

Solution 2:

<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.


Solution 3:

Use Jquery :

$(document).ready(function(){
    $("#DropDownID").change(function () {
           // Your requirment
     });
});

Also it's always better to write it inside the document.ready


Solution 4:

Use something like this (uses jQuery):

$(document).ready(function() {
    $("#dropdownId").change(function(e)) {
             do something...
    });
});

Solution 5:

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.


Post a Comment for "How To Call A Javascript Function Using Asp.net Dropdown List"