문제

In this custom select box, I am trying to show a list of options where a selection shows its corresponding data-icon and not its text in the placeholder.

But the data-icon is not updating properly in the placeholder when one of the selected options is clicked. It only shows the first data-icon irrespective of what is selected.

http://jsfiddle.net/Zg76F/3/

on line 7 - declaration
dataui = $(this).children('option')

on line 24 - show data-icon for option:selected on first run
$styledSelect.html('<img src="'+dataui.data('icon')+'" />');

on line 61 - update selection when option is clicked
$styledSelect.html('<img src="'+dataui.data('icon')+'" />').removeClass('active'); 

I guess the prob is in the declaration, but not sure how to iterate and point to a particular selection.
and
I am not able to fit option:selected in line 24 to show data-icon on first run.

and, how will I also add a tick mark when the option list is shown to indicate what was/is selected

도움이 되었습니까?

해결책

you need to set the $styledSelect.html with the $this.find(":selected").data('icon') like this

$('select').each(function() {
    var $this = $(this),
    dataui = $this.children('option'),
    numberOfOptions = dataui.length;
    $this.addClass('s-hidden');
    $this.wrap('<div class="select"></div>');
    $this.after('<div class="styledSelect"></div>');
    var $styledSelect = $this.next('div.styledSelect');
    //$this.find(":selected").data('icon') the actual icon
    $styledSelect.html('<img src="'+$this.find(":selected").data('icon')+'" />');
    var $list = $('<ul />', {
        'class': '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);
    }
    var $listItems = $list.children('li');
    $styledSelect.mouseover(function(e) {
        e.stopPropagation();
        $('div.styledSelect.active').each(function() {
            $(this).removeClass('active').next('ul.options').hide();
        });
    $(this).toggleClass('active').next('ul.options').toggle();
    });
$listItems.click(function(e) {
    e.stopPropagation();
    //select the option
    $this.val($(this).attr('rel'));
    //set the icon
    $styledSelect.html('<img src="'+$this.find(":selected").data('icon')+'" />').removeClass('active'); 
    $list.hide();   
 });
$('.select').mouseleave(function() {
    $styledSelect.removeClass('active');
    $list.hide();
});

});    

http://jsfiddle.net/Zg76F/4/

다른 팁

jquery has a :selected option that you should use http://api.jquery.com/selected-selector/

when X option is selected, append the check mark image to the option then change the data icon.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top