Is it possible to convert a select menu to buttons? (ok)

https://stackoverflow.com/questions/18931628/is-it-possible-to-convert-a-select-menu-to-buttons

<select name="text">
     <option>Yes</option>
     <option>No</option>
     <option>Maybe</option>
     <option>Perhaps</option>
</select>
/*var buttons = "";
$("select option").each(function () {
    buttons += "<input type='button' value='" + this.value + "'/>";    
});

$("select").replaceWith(buttons);
*/

var selectName = $('select').attr('name');
colso

// add a hidden element with the same name as the select
var hidden = $('<input type="hidden" name="'+selectName+'">');
hidden.val($('select').val());
hidden.insertAfter($('select'));

$("select option").unwrap().each(function() {
    var btn = $('<div class="btn">'+$(this).text()+'</div>');
    if($(this).is(':checked')) btn.addClass('on');
    $(this).replaceWith(btn);
});

$(document).on('click', '.btn', function() {
    $('.btn').removeClass('on');
    $(this).addClass('on');
    $('input[name="'+selectName+'"]').val($(this).text());
});
div.btn {
    display: inline-block;
    border: 2px solid #ccc;
    margin-right: 5px;
    padding: 2px 5px;
    cursor: pointer;
}
div.btn.on {
    background-color: #777;
    color: white;
}

Last updated