开发者

Select list scroll to a specific option element

开发者 https://www.devze.com 2023-03-19 05:08 出处:网络
I have a select box with years. First option is empty. When I click on select list I want scrollbar to scroll automaticaly down . I\'ve tried with scrollTop but it\'s working only in FireFox.

I have a select box with years. First option is empty. When I click on select list I want scrollbar to scroll automaticaly down . I've tried with scrollTop but it's working only in FireFox.

Ex:

<select id="mySelect">
<option selected="selected" value=""></option>
<option value="1911">1911</option>
<option value="1912">1912</option>
<option value="1913">1913</option>
<option value="1914">1914</option>
<option value="1915">1915</option>
<option value="1916">1916</option>
<option value="1917">1917</option>
<option value="1918">1918&开发者_如何学运维lt;/option>
<option value="1919">1919</option>
<option value="1920">1920</option>
<option value="1921">1921</option>
<option value="1922">1922</option>
...

</select>


Select click/focus is a bit more complicated, actually. This is what you want:

$('#mySelect').focus(function(){

    if($(this).data('focused') !==  true)
    {
        $(this).data('focused',true);  
        $(this).children(':last-child').prop('selected',true);
    }

});

$('#mySelect').blur(function(){
    $(this).data('focused',false); 
});

Working example: http://jsfiddle.net/AlienWebguy/zuJrK/


Try the below code I hope it helps

$("#mySelect").click(function(){
   $(this).find("option").eq(someMiddleNumber).focus().blur();
});


You may try to remove the style "overflow-y:auto;" from css, that will keep the selected item scroll into the view (when you use arrow keys to change the selection).


Some improvement to AlienWebguy's answer:

You can make sure the default value will stay selected in case user does not make any changes by adding the settimeout section below:

if($(this).data('focused') !==  true)
{
    $(this).data('focused',true);  
    $(this).children(':last-child').prop('selected',true);
    // dirty workaround
    window.setTimeout(function(){
        $(this).val("");
    }, 50);
}


ShankarSangoli was close but I think you want:

$("#mySelect").click(function(){
   $(this).find("option:last").attr("selected","selected");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消