Reset Multiple Control Types | Bootstrap Modal

Use jQuery to reset different controls (text, checkbox, select, multiple-select) in bootstrap's modal.

by bmarsh123

HTML

<link rel="stylesheet" href="http://twitter.github.io/bootstrap/assets/css/bootstrap.css">
<script src="http://twitter.github.io/bootstrap/1.4.0/bootstrap-modal.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<form id="myForm">
    <a id="openModal" style="text-decoration: none;" data-controls-modal="myModal" href="#" data-backdrop="true" data-keyboard="true"><button class="btn">Open Modal</button></a>
    
    <div id="myModal" class="modal hide fade in">
        <div class="modal-header">
            <a class="close" href="#">x</a>
            <h3>Modal Header</h3>
        </div>
        <div class="modal-body">
            <input type="text" id="input1" placeholder="Enter text here..." />
            <br />
            <div class="row-fluid"><input type="checkbox" id="cb1" />
                <label id="lbl1">Unchecked</label></div>
            <br />
            <select id="sel1" multiple="multiple" class="sel">
                <option>Value 1</option>
                <option>Value 2</option>
                <option>Value 3</option>
            </select>
            <br /><br />
            <select id="sel2" class="sel">
                <option>Value 1</option>
                <option>Value 2</option>
                <option>Value 3</option>
            </select>
        </div>
        <div class="modal-footer">
            <a href="#" class="close">Close</a>
        </div>
    </div>
</form>

CSS

body {
    margin: 20px;
}
label {
    display: inline;
}

JavaScript

// Position modal on screen appropriately
$('body').on('show', '.modal', function(){
    $(this).css({
        'margin-top': ($(window).height() - $(this).height()) / 2,
        'top': '0',
        'margin-left': ($(window).width() - $(this).width()) /2,
        'left': '0'
    });
});
$('body').on('hidden', '.modal', function() {
    $('#myModal .sel:not([multiple])').prop('selectedIndex', 0);
    $('#myModal input[type=text]').val("");
    $('#myModal input[type=checkbox]').prop('checked', false);
    $('#sel1').trigger('change').find('option').prop('selected', false);
    $('#lbl1').text('Unchecked');
});
$('#cb1').change(function() {
    if ($(this).is(':checked')) {
        $('#lbl1').text('Checked');
    } else {
        $('#lbl1').text('Unchecked');
    }
});