Gmail就像全选复选框一样

时间:2016-06-02 16:49:26

标签: javascript html

有人拥有在索引页面中实现“全选”复选框的Javascript代码,带有分页,这也允许您选择所有页面中的所有记录,而不仅仅是显示的那些,就像gmail网页所做的那样单击左上角的ALL复选框:

option to select all message allows you to select all records

1 个答案:

答案 0 :(得分:3)

在你的后端获取“all_records”'字段以标识所有记录(不仅仅是页面中的复选框)。 写入' total_records'输入所有记录的总和,不加分页。

请尝试以下代码:

HTML:

<form action="#">
    <p><label><input type="checkbox" id="check_all"/> Check all</label>
    <input id='total_records' type="hidden" value='50'/>
    <input id='all_records' type="hidden" value='0'/>
    <label id='all_records_message' class='check_message' style='display:none'>Todas os <b class='total_pagina'></b> registros dessas pagina foram selecionados
      <a id= 'all_records_link' href="#">Selecione todos os registros <b class='total_consulta'></b> da
      consulta</a>
    </label>
    <label id='no_records_message' class='check_message' style='display:none'>Todas os <b class='total_consulta'></b> registros estão selecionados
      <a id= 'no_records_link' href="#">Limpar a seleção</a>
    </label>   
    </p>
    <fieldset class='check_itens'>
        <legend>Loads of checkboxes</legend>
        <p><label><input type="checkbox" /> Option 1</label></p>
        <p><label><input type="checkbox" /> Option 2</label></p>
        <p><label><input type="checkbox" /> Option 3</label></p>
        <p><label><input type="checkbox" /> Option 4</label></p>
    </fieldset>
</form>

Javascript(JQuery):

function check_all_click() {
    if ($('#check_all').prop("checked")) {
            $('#all_records_message').show();
        } else {
            $('#all_records_message').hide();
            $('#no_records_message').hide();
            $('#all_records').val(0);
        }
}

$(document).ready( function() {
    $('.check_message > b.total_pagina').html($('.check_itens :checkbox').length);
    $('.check_message > b.total_consulta').html($('#total_records').val());

});

$("#check_all").change(function () {
        $("input:checkbox").prop('checked', $(this).prop("checked"));
        check_all_click();
});

$('#all_records_link').click( function() {
    $('#all_records').val(1); 
    $('#all_records_message').hide();
    $('#no_records_message').show();
});

$('#no_records_link').click( function() {
    $('#all_records').val(0);
    $('#no_records_message').hide();
    $('#check_all').trigger('click');
});

$('.check_itens :checkbox').change(function () {
    if ($('#check_all').prop("checked")) {
        $("#check_all").prop('checked', false);
        check_all_click();
    }
    if ($('.check_itens :checkbox').length == $('.check_itens :checkbox:checked').length) {
        $('#check_all').trigger('click');
    }
});

CSS:

.check_message {
    display: block;
    background-color: #ffc;
    color: #222;
    padding: 3px 8px;
    font-size: 90%;
    text-align: center;
    font-family: arial, sans-serif;
}

见工作: https://jsfiddle.net/pv57hx3h/