View on GitHub

Tutorial Part Four

Using a custom renderer.

Rendering elements

The component has many options to choose from. Look at the way we are now creating the component:

js/script.js

We group the results by Continent. We use custom renderers to change the way that elements appear in the combo and once they have been selected:

$(function() {

    $('#ms').magicSuggest({
        data: 'get_countries.php',
        valueField: 'idCountry',
        displayField: 'countryName',
        groupBy: 'continentName',
        renderer: function(data){
            return '<div class="country">' +
                '<img src="img/flags/' + data.countryCode.toLowerCase() + '.png" />' +
                '<div class="name">' + data.countryName + '</div>' +
                '<div style="clear:both;"></div>' +
                '<div class="prop">' +
                    '<div class="lbl">Population : </div>' +
                    '<div class="val">' + data.population + '</div>' +
                '</div>' +
                '<div class="prop">' +
                    '<div class="lbl">Capital : </div>' +
                    '<div class="val">' + data.capital + '</div>' +
                '</div>' +
                '<div style="clear:both;"></div>' +
            '</div>';
        },
        selectionRenderer: function(data){
            var img = data.countryCode ? ('<img src="img/flags/' + data.countryCode.toLowerCase() + '.png" />') : '';
            return img + '<div class="name">' + data.countryName + '</div>';
        }

    });

});

css/style.css

We make some changes here so that our results look presentable

body{
    background: #EEE;
}
.container{
    max-width: 500px;
    border-radius: 5px;
    background: #FFF;
    border: 1px solid #CCC;
    min-height: 400px;
    margin-top: 50px;
}
.country{
    margin-bottom: 5px;
}
.country img{
    float: left;
    position: relative;
    top: 7px;
    margin-right: 10px;
}
.country .name{
    font-weight: bold;
    color: #333;
}
.country .prop{
    float: left;
    width: 50%;
}
.country .prop .lbl{
    font-size: 11px;
    line-height: 11px;
    float: left;
    color: #AAA;
    margin-left: 25px;
    margin-right: 5px;
}
.country .prop .val{
    font-size: 11px;
    line-height: 11px;
    color: #666;
}

.ms-sel-item img{
    float: left;
    position: relative;
    top: 3px;
    margin-right: 3px;
}
.ms-sel-item .name{
    float: left;
}