views:

43

answers:

1

i have a multiple select tag

<select multiple="multiple" size="5" id="cities_select">
     <option value="1">city1</option>
     <option value="2">city2</option>
     <option value="3">city3</option>
     <option value="4">city4</option>
     <option value="5">city5</option>
     <option value="6">city6</option>
     ................................
</select>

i need to have max 5 selected elements, ie

if i have selected 1,2,3,4,5 elements, onselect od 6th element i need to remove selected attribute of first, ie, i must get 2,3,4,5,6 selected elements.

and now, what is the problem, if i have selected 2,3,4,5,6 for example, onselect of first i must remove selected attribute of last selected element, and get 1,2,3,4,5 selected list. how can i get that effect?(i can't fix the element, which edited last).

$("#supply_cities_select").change(function()
        {
            var a = $("#supply_cities_select :selected").length;
            if(a > 5)
            {
                //i don't know what to write here:(
            }
        })

Any ideas?

Thanks

A: 

To get such effect i can't help use .change method, so i wrote the function onclick event

$("#supply_cities_select option").click(function()
        {
            var clicked = 0;
            if($(this).attr("selected")) 
            {
                clicked = $(this).val();
            }
            if(clicked != 0)
            {
                var a = $("#supply_cities_select :selected").length;
                 end = $("#supply_cities_select :selected").slice(-1).map(function(i) {
                      return this.value;
                  }).get().join('');
                if(a > 5)
                {
                    var v1 = parseInt(clicked);
                    var v2 = parseInt(end);
                    if(v1 < v2)
                    {
                        $("#supply_cities_select option[value='"+v2+"']").attr("selected",false);

                    }
                    if(v1 == v2)
                    {
                        $("#supply_cities_select :selected:lt(1)").attr("selected",false);
                    }

                }
            }
        });

you can see the demo here

Syom