skip to Main Content

I’ve tried the following but they return the list of select values not the option that fired the onchange event. How can I identify the selected option’s value that fired the event?

$('#ddlCostCenters').on('change', function (e) {
   alert($(this).val());           //returns the list of selected
   alert(e.currentTarget.value);   //returns the list of selected
});

2

Answers


  1. Chosen as BEST ANSWER

    The function signature is the key. Parm names element and checked provide what is needed.

    The following is a great source for learning how bootstrap works Bootstrap multi-select

    onChange: function(element, checked) {
        if (checked === true) {
            if ($('#ddl1 option[value=' + element.val() + ']:selected').length > 0){
                alert("Options are mutually exclusive. Selection canceled...");
                $('#ddl1').multiselect('deselect', element.val());
            }
        }
    },
    

  2. Below is a work demo to get the value of the currently selected option , you can refer to it.

    Brand:

     public class Brand
        {
            [Key]
            public int Id { get; set; }
            [Required]
            public string Name { get; set; }
        }
    

    VehicleVM:

    public class VehicleVM
        {             
            public IEnumerable<SelectListItem> BrandList { get; set; }
        }
    

    Controller:

    public IActionResult Index()
            {
                var brands = new List<Brand>();
                brands.Add(new Brand() { Id = 1, Name = " brand1" });
                brands.Add(new Brand() { Id = 2, Name = "brand2" });
                var BrandList = new SelectList(brands, "Name", "Name");
                var model = new VehicleVM();
                model.BrandList=BrandList;  
                return View(model);
            }
    

    Index view:

    @model VehicleVM
    @Html.ListBoxFor(model => model.BrandList, new MultiSelectList( Model.BrandList, "Value", "Text"), new {  multiple = "multiple",id = "ddlCostCenters" })
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
     $('#ddlCostCenters').on('change', function (e) {
            alert($(this).val());           //returns the list of selected           
        });
    </script>
    

    result:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search