简体   繁体   中英

Display the alert box when change the @html.DropDownList value

  @Html.DropDownListFor(model => model.Status, new List<SelectListItem> 
       { new SelectListItem{Text="Active", Value="1",Selected =true},
         new SelectListItem{Text="Deactive", Value="0"}})

If i change the value Active to De active display the one alert box. How to display the alert box.

You could use the change() handler in Jquery to listen for the event.

$( "#targetId").change(function() {
     alert( "Something changed handle it here" );
});

http://api.jquery.com/change/

  Razor:-


 @Html.DropDownListFor(model => model.Status, new List<SelectListItem> 
               { new SelectListItem{Text="Active", Value="1",Selected =true},
                 new SelectListItem{Text="Deactive", Value="0"}})

Jquery(Change event is called when you change the dropdownlist value whose id is attached in below query) :-

 <script>

    $(document).ready(function(){
        $('select#status').change(function() {
            alert("value changed. New value is " + $(this).val());
    });
    });
});

</script>

Add this code in your master layout or in view in which Dropdown is:

First Way:

Jquery CODE:

<script>

    $(document).ready(function(){

     $('select#status').change(function() {
            alert($(this).val());
    });
});

</script>

Second Way:

Or you can add your own id like this:

 @Html.DropDownListFor(model => model.Status, new List<SelectListItem> 
               { new SelectListItem{Text="Active", Value="1",Selected =true},
                 new SelectListItem{Text="Deactive", Value="0"}
               },
                 null,
                 new {@id="DDLStatus"})

and script:

  <script>

        $(document).ready(function(){

         $('select#DDLStatus').change(function() {
                alert($(this).val());
        });
    });

    </script>

Note: make sure that jquery script file is included in your master layout mostly it is in View --> Shared --> _Layout.cshtml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM