我有这个jQuery代码:
$('button#btnBuscar').on('click', function (ev) {
ev.preventDefault();
$.post(Routing.generate('filtrarNormas'), $('#buscadorNorma').serialize(), 'json')
.done(function (data, textStatus, jqXHR) {
if (data.entities.length > 0) {
$('#resultadoNorma').show();
var $html = '';
data.entities.forEach(function (value, index, array) {
$html += '<tr>';
$html += '<td><input type="checkbox" value="' + value.id + '"></td>';
$html += '<td>' + value.codigo + '</td>';
$html += '<td>' + value.norma + '</td>';
$html += '<td>' + value.anno + '</td>';
$html += '<td>' + value.comiteTecnico + '</td>';
$html += '</tr>';
});
$("table tbody#resultadoNormaBody").html($html);
}
})
.fail();
});
上面代码的目的是执行Ajax调用并在JSON响应中呈现许多tr
值,这很好。现在您可以看到每次迭代的第一列都有一个复选框,对吗?
我需要做的是在选中当前复选框时复制完整行(tr)并附加到另一个表,而不重复相同内容而不删除其他表内容。可能有很多可能的解决方案,但现在(根据@ josh-kg)建议其中一个可以标记复选框并立即克隆当前的tr
元素,它会起作用,是的,但如果发生了我多次切换复选框?同一行将附加到#newTable
,并不是主意。使用提供的此解决方案,然后我应该切换到克隆,以便追加/删除克隆的tr
。
我在考虑有一个按钮(button#btnAplicarNorma
),默认情况下已禁用,如果我至少标记了一个复选框,则启用它并在按钮的单击事件上通过迭代每个按钮来执行克隆部分标记的复选框,如:
$('button#btnAplicarNorma').on('click', function (ev) {
// check if at least there is one checkbox marked and enable the button
// check which checkboxes are marked and clone the current element
})
但我怎么能这样做?
注意:tr
应该克隆的表格不在模式本身但在同一页面中,所以这不应该是一个问题
答案 0 :(得分:1)
$('#resultadoNormaBody').on('change','input[type=checkbox]',function(){
var my_checkbox = $(this);
if (my_checkbox.is(':checked')) {
my_checkbox.closest('tr').clone().appendTo('#newtable');
}
});
更新(在OP对预期行为做出一些澄清之后):
要在默认情况下禁用该按钮,请在HTML标记中包含disabled属性:
<button id="btnAplicarNorma" disabled>Copy Rows</button>
然后,要在选中至少一个复选框时启用该按钮:
$('#resultadoNormaBody').on('change','input[type=checkbox]',function(){
var $my_checkbox = $(this);
var $my_tr = $my_checkbox.closest('tr');
if ( $my_checkbox.prop('checked') ) {
// Add the class to mark that it should be copied later when button clicked
$my_tr.addClass('copyMe');
}
var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]');
// Loop through checkboxes to see if one is checked
$all_checkboxes.each(function() {
// if one checkbox is checked, enable button and end the .each loop
if ( $(this).prop('checked') ) {
$('#btnAplicarNorma').prop('disabled',false);
return false;
}
// If we didn't catch any checked boxes earlier, disable the button
$('#btnAplicarNorma').prop('disabled',true);
});
});
$('#btnAplicarNorma').on('click', function (ev) {
var $tr_to_append = $('#resultadoNormaBody').find('tr.copyMe');
// is there's a tr to copy, clone it, append, and remove the copyMe classes
if ( $tr_to_append.length ) {
// first uncheck all the checkboxes
$tr_to_append.find('input[type=checkbox]').prop('checked',false);
// copy and append and remove class
$tr_to_append.clone().appendTo('#newtable').removeClass('copyMe');
$tr_to_append.removeClass('copyMe');
// disable the button again
$(this).prop('disabled',true);
}
});