2015-08-26 4 views
0

Для каждой записи в моем <table> У меня есть флажок. Когда этот флажок щелкнул, значение ID посылается в массив для записи, что проверяется:Заполнение массива с помощью «Выбрать все» Флажок

function setIds(){ 
var recordIds = []; //array to store IDs 
$(".row-check").change(function(e){ 
    var checkedRecord = dataTable.getRecord(e.currentTarget.id); //gets ID of record object 
    var id = checkedRecord.toJSON().id; 
    if(this.checked){ 
     recordIds.push(id); 
    } else { // Return array record ID that was unchecked 
     recordIds.splice($.inArray(id, recordIds), 1); 
    } 
    console.log(recordIds); 
}); 
} 

У меня также есть флажок в моем заголовке таблицы, которая проверяет все записи на столе:

function selectAll(){ 
    $('input[name="all"]').click(function() { 
     $('input[name="row-check"]').prop('checked', this.checked); 
    }); 
} 

Вот как таблица выглядит (Потому что мне нравится болван) enter image description here

Однако функция .change() не подхватывает запись выбранной когда я выбираю «выбрать все» флажок. Я попытался установить метод .row-check .change() в моей функции selectAll, но не повезло. Как я могу отправить все свои идентификаторы в массив, когда установлен флажок «Выбрать все»?

+1

Будьте осторожны с вашим 'splice()' ... если этот идентификатор не находится в массиве, это приведет к хаосу с использованием '-1' в качестве значения сплайсинга – charlietfl

+1

http://stackoverflow.com/questions/4247264/how -в-триггер-JQuery-изменение-событие-в-код –

ответ

2

Самым простым решением было бы, чтобы вызвать change событие на измененных-входов, внутри selectAll() Funcition, который затем будет пойманной – и обрабатываются – функцией change слушателя setIds():

function selectAll(){ 
    $('input[name="all"]').click(function() { 

     // using the change() method - with no arguments - to fire 
     // the change event, which is caught - and handled - by the 
     // named change event-handler function: 
     $('input[name="row-check"]').prop('checked', this.checked).change(); 
    }); 
} 

A простое доказательство правильности концепции того, как приведенный выше код может работать на практике (хотя и в ограниченной функциональности демонстрации):

// caching the 'child' inputs: 
 
var childInputs = $('input[type=checkbox].childInput'); 
 

 
// a simple change-handler function to demonstrate: 
 
function changeHandler() { 
 
    $(this).closest('li').toggleClass('checked', this.checked); 
 
} 
 

 
// binding the change-handler function to the childInputs: 
 
childInputs.on('change', changeHandler); 
 

 
// binding an anonymous 'check-all' function to the 'all'/'parent' checkbox: 
 
$('input[name=all]').on('change', function() { 
 
    
 
    // setting the checked property of each of the childInput elements 
 
    // equal to the changed 'parent' checked-state, and 
 
    // firing the 'change' event on each of those childInputs 
 
    // to allow their change-handler to process/deal with the event: 
 
    childInputs.prop('checked', this.checked).change(); 
 
});
li { 
 
    border: 2px solid transparent; 
 
    margin-bottom: 0.2em; 
 
} 
 
.checked { 
 
    border-color: limegreen 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li> 
 
    <input type="checkbox" name="all"> 
 
    <label for="">All</label> 
 
    <ul> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input1" class="childInput">input 1</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input2" class="childInput">input 2</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input3" class="childInput">input 3</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input4" class="childInput">input 4</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input5" class="childInput">input 5</label> 
 
     </li> 
 
    </ul> 
 
    </li> 
 
</ul>

И понятия доказательства правильности того, как проверка, или убрав, все «ребенок» <input> элементов может служить надлежащим образом проверить, или снимите флажок, то «проверить все» <input>:

var childInputs = $('input[type=checkbox].childInput'); 
 

 
function changeHandler() { 
 
    $(this).closest('li').toggleClass('checked', this.checked); 
 

 
    // finding out whether the number of childInputs is equal to the nummber 
 
    // of checked childInputs; if it is the assessment returns true (if not 
 
    // it returns false): 
 
    var check = childInputs.length == childInputs.filter(':checked').length; 
 
    
 
    // here we set the checked property of the 'all' checkbox to be equal to 
 
    // the Boolean (true/false) value of the 'check' variable. Note that because 
 
    // we're inside of the changeHandler function we do not want to trigger the 
 
    // change event of the 'all' checkbox, which would then iterate over all 
 
    // the childInputs and fire their change-handler again which would then 
 
    // refire the 'change' event on 'all' checkbox (again and again and again...): 
 
    $('input[name=all]').prop('checked', check); 
 
} 
 

 
childInputs.on('change', changeHandler); 
 

 
$('input[name=all]').on('change', function() { 
 
    childInputs.prop('checked', this.checked).change(); 
 
});
li { 
 
    border: 2px solid transparent; 
 
    margin-bottom: 0.2em; 
 
} 
 
.checked { 
 
    border-color: limegreen 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li> 
 
    <input type="checkbox" name="all"> 
 
    <label for="">All</label> 
 
    <ul> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input1" class="childInput">input 1</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input2" class="childInput">input 2</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input3" class="childInput">input 3</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input4" class="childInput">input 4</label> 
 
     </li> 
 
     <li> 
 
     <label> 
 
      <input type="checkbox" value="input5" class="childInput">input 5</label> 
 
     </li> 
 
    </ul> 
 
    </li> 
 
</ul>

Упрощенная проверка концепции внешней JS Fiddle demo для экспериментов и развития.

Ссылки

Смежные вопросы