Rohit416
Rohit416

Reputation: 3496

limit the items to show in HTML drop down list when it opens

I have 10 items in drop down and want to display only first 5 when i open the drop down list and rest of the items should remain in scroll.

I have the following code to control the size in JS.

$(function(){
  $("#myList").click(function(){
    $(this).attr('size', '5');
  });
});

Setting the following in HTML...

<select size="5">
  <option value=""></option>
  ...
</select>

will make the drop down to always appear with 5 items as default and browsers may handle this their own way so i thought of doing it via JS.

The problem with this is it open with 5 items but did not close automatically as what a normal drop down does, until page get refreshed (obviously). Please advise.

Upvotes: 1

Views: 4361

Answers (2)

Rohit416
Rohit416

Reputation: 3496

However the accepted solution worked just fine but only for jQuery versions prior to 1.9 because hover has been deprecated from this version henceforth.

But you can use make the hover() and other deprecated features work using jQuery migrate plugin if you do not want to switch to a newer version.

An alternative solution for higher versions of jQuery i.e. v1.9 +

$(function(){
  $("#myList").on({
    mousedown: function(){
      $(this).attr('size', '5');
    },

    mouseleave: function(){
      $(this).removeAttr('size');
    }
  });
});

Here is a working DEMO.

Upvotes: 0

Curtis
Curtis

Reputation: 103388

You could change the list so that it displays multiple items, and then only shows the selected when hover is removed:

$(document).ready(function(){

$("#mylist").hover(function(){

$(this).attr('size', '5');
},function(){
 $(this).removeAttr("size");   
});

});​

-- SEE DEMO --

Upvotes: 3

Related Questions