You can not really open select
programmatically. This is a constraint imposed by the browser policy, where there must be direct user interaction.
However, there are ways to manipulate the element to "simulate" as if select
has been clicked and expanding it. The most common is to transform it into a listbox , by adding the property size
.
To get away from the ordinary, I have created a script that may apply to you. It consists of simulate a "false select" that applying CSS styles is almost identical to the original select
both visually and functionally.
See an example with the commented code:
$(document).ready(function(){
function fakePop(el){
// populo o falso select
var val = el.find("option:selected").text();
var opcoes = '';
$.each(el.find("option"), function(e,t){
var sel = $(t).text() == val ? ' class="selected"' : '';
$("#fake_select").append('<li'+sel+'>'+$(t).text()+'</li>');
});
}
$("#fake_select").on("mouseleave", function(){
$("#fake_select").html('');
var el = $("#exemplo1");
fakePop(el);
});
// esconder o falso select
function hideFakeSelect(){
$("#fake_select").hide().html('');
}
$("#exibir").click(function(){
var el = $("#exemplo1");
if(!$("#fake_select").is(":visible")){
// ajusto a posição e o tamanho do falso select
$("#fake_select").css({
"top": el.height()+"px",
"width": el.width()+"px"
}).show();
fakePop(el); // populo o falso select
}else{
// escondo o falso select se ele estiver visível
hideFakeSelect();
}
});
$(document).on("click mouseover", "#fake_select li", function(e){
// escondo o falso select ao clicar em uma opção
if(e.type == "click"){
$('#exemplo1').val($('#exemplo1 option:contains('+$(this).text()+')').val());
}else{
// efeito hover
$("#fake_select li")
.removeClass("selected")
.not($(this));
}
}).on("click", function(){ // escondo o falso select ao clicar em uma opção ou em outro lugar da página
hideFakeSelect();
});
// evito que o falso select feche ao clicar no botão
$("#exibir").click(function(e){
e.stopPropagation();
});
});
*{
position: relative;
}
#fake_select{
display: none;
position: absolute;
left: 0;
z-index: 99;
background: #fff;
border: 1px solid #999;
}
#fake_select li{
list-style: none;
padding: 0 3px;
cursor: default;
}
#fake_select .selected,
#fake_select li:hover{
background: #3f81fb;
color: #fff;
}
#exemplo1:focus + #fake_select{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><selectname="exemplo1" id="exemplo1">
<option value="">Selecione</option>
<option value="1">Caique</option>
<option value="2">Natane</option>
</select>
<span id="fake_select"></span>
</div>
<br>
<div>
<button name="exibir" id="exibir">
Expandir select e exibir opções
</button>
</div>