Created
March 5, 2016 13:32
-
-
Save alizhdanov/d3bfd1027930566775b6 to your computer and use it in GitHub Desktop.
Form select customize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('select').each(function(){ | |
var $this = $(this), | |
numberOfOptions = $(this).children('option').length; | |
$this.addClass('select-hidden'); // скрываем селект | |
$this.wrap('<div class="select"></div>'); // оборачиваем селект в див | |
$this.after('<div class="select-styled"></div>'); // после селекта добавляем класс который иммитирует сам селект | |
var $styledSelect = $this.next('div.select-styled'); // выбираем иммитирующий селект блок | |
$styledSelect.text($this.children('option').eq(0).text()); // добавляем ему текст от первого option'a | |
var $list = $('<ul />', { | |
'class': 'select-options' | |
}).insertAfter($styledSelect); // добавляем список после дива иммитируещего селект | |
for (var i = 0; i < numberOfOptions; i++) { | |
$('<li />', { | |
text: $this.children('option').eq(i).text(), | |
rel: $this.children('option').eq(i).val() | |
}).appendTo($list); | |
} // прогоняем все option и передаем их значение в список | |
var $listItems = $list.children('li'); // создаем переменную обозначающую эллемент списка | |
$styledSelect.click(function(e) { | |
e.stopPropagation(); | |
$('div.select-styled.active').each(function(){ | |
$(this).removeClass('active').next('ul.select-options').hide(); | |
}); | |
$(this).toggleClass('active').next('ul.select-options').toggle(); | |
}); | |
$listItems.click(function(e) { | |
e.stopPropagation(); | |
$styledSelect.text($(this).text()).removeClass('active'); | |
$this.val($(this).attr('rel')); | |
$list.hide(); | |
//console.log($this.val()); | |
}); | |
$(document).click(function() { | |
$styledSelect.removeClass('active'); | |
$list.hide(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment