Domanda

I have this dropdown

   Sort by: @Html.DropDownListFor(model => model.SortBy, Model.LotSortings, "Relevance", new { @class = "form-control", @id="sort_ddl" })

and I want to call a get action method (not an Ajax method) whenever I change the selection from one option to a different one.

I'd love to be shown how I can solve that too but as a first step towards this goal I created this script at the top of the page

<script>
    $('#sort_ddl').change(function () { alert('hi'); })
</script>

This does get called but only on page load and at that point it does not alert. It never gets called on selection change.

How can I solve this?

È stato utile?

Soluzione

Add your method in document.ready function. It will attach the change event to element when DOM is ready.

<script>
    $(document).ready(function () {
        $('#sort_ddl').change(function () {
            alert('hi');
        })
    });
</script>

Altri suggerimenti

You can also try:

<script>
   $(document).ready(function () {
      $('#sort_dll').on('change', function() {
         alert( 'hi' );
      })
   });
</script>

For dynamically added , use .on

<script>
    $(document).ready(function () {
        $('body').on('#sort_ddl','change' ,function () {
            alert('hi');
        })
    });
</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top