1

I want to sort my List box based on the selected value of my Dropdown list, Is there a way to do this with Jquery or Javascript?

This is my View List Box and Selected List:

 <select id="sel2">
 <option value="">Todos</option>
 <option value="COMIDAS">COMIDAS</option>
 <option value="DESAYUNOS">DESAYUNOS</option>
 <option value="CENAS">CENAS</option>
 </select>

 <select id="Group" multiple="multiple" name="Group" style="width: 300px;">
 <option>{ Turno = CENAS, Total = $57,410.00 }</option>
 <option>{ Turno = COMIDAS, Total = $151,571.00 }</option>
 <option>{ Turno = DESAYUNOS, Total = $58,994.00 }</option>
 </select>
                                             

My List box is filled Before Page load on ServerSide by a Viewbag

ViewBag on Controller:

foreach (var item in db.Pos.Where(r => r.Fecha.Day <= today.Day).Select(v => new { Rid = v.Rid, Total = v.Total })
 .GroupBy(l => l.Rid).AsEnumerable().Select(z => new {Turno=z.Key, Total = String.Format("{0:$#,##0.00;($#,##0.00);Zero}",Decimal.Round(z.Sum(l => l.Total), 0) )}))
        {

            listadesumas.Add(item.ToString());
            //listadesumas.Add(Selected);          
        }

        var grupos = new SelectList(listadesumas.ToList());
        ViewBag.Group = grupos;

Viewbag on View:

@Html.ListBox("Group", (IEnumerable<SelectListItem>)ViewBag.Group, new { style = "width: 300px;" })
tereško
  • 58,060
  • 25
  • 98
  • 150
Arturo Martinez
  • 389
  • 7
  • 28

2 Answers2

1

Use Jquery to sort your dropdownlist based on the first dropdown selection

    $('#sel2').change(function(e) {
        $("#Group").html($('#Group').sort(function(x, y) {
            return $(x).val() == $("#sel2").val() ? 1 : -1;
        }));
        $("#Group").get(0).selectedIndex = 0;
        e.preventDefault();
    });

Also you will need to add the same values from the first dropdown to the second dropdown as I see your second dropdown has no values.

James Dev
  • 2,979
  • 1
  • 11
  • 16
  • the listbox has no values because i fil it by a Viewbag, i dont know how to add it values i have edited the question for you to see the Listbox code – Arturo Martinez Mar 08 '16 at 18:07
  • You will need to build the SelectListItem where you can set your Text and Value properties then add it to your SelectList. Please see this question for more help on how to do this http://stackoverflow.com/questions/1820368/value-text-for-generated-selectlist – James Dev Mar 09 '16 at 11:46
0

Using JQuery or JavaScript, set an on-change event handler on your drop-down list.

Inside the event handler, examine the selected value and use conditional statements to re-arrange the items in your list box.

Here is an example of how to set an event handler for a drop-down list using JQuery.

Here is an example of how to sort the contents of a select box.

Community
  • 1
  • 1
Robert
  • 371
  • 1
  • 7