У меня есть динамически сгенерированная таблица с фильтром для выбора столбцов, которые будут видны. Мне нужно динамическое число видимых в таблице c столбцов, которые затем будут передаваться в другую часть кода, однако используемая мной кодировка не обновляет счетчик, когда я изменяю столбцы, видимые с помощью фильтра.
Я попробовал два подхода, чтобы получить количество столбцов:
1) Количество выбранных опций фильтра столбцов:
jQuery(document).ready(function ($) {
var OptionSelected = $("#ColumnCheckbox option:selected").length;
console.log(OptionSelected);
});
2) Количество головок столбцов:
jQuery(document).ready(function ($) {
var ColumnsSelected = $("table.CompTable thead > tr > th:not(:first)").length;
console.log(ColumnsSelected);
});
Однако в обоих случаях количество не изменяется при фильтрации столбцов. (Счетчик отображается в «консоли» в рабочем коде ниже)
Есть ли другой способ, которым я могу заставить счетчик динамически изменять каждый раз, когда столбцы увеличиваются или уменьшаются?
Завершить работу код ниже:
jQuery(document).ready(function($) {
var StatJSON = {
"Samsung": {
"Ranking": '#3',
"Rating": '2.5',
"Distance": '30',
"Time to Travel": '400',
"Altitude (meter)": '200',
"Area": '250'
},
"Mi": {
"Ranking": '#2',
"Rating": '3.5',
"Distance": '20',
"Time to Travel": '150',
"Altitude (meter)": '0',
"Area": 'NA'
},
"Apple": {
"Ranking": '#1',
"Rating": '4.5',
"Distance": '50',
"Time to Travel": '300',
"Altitude (meter)": 'NA',
"Area": '200'
},
"LG": {
"Ranking": '#1',
"Rating": '4.5',
"Distance": '50',
"Time to Travel": '300',
"Altitude (meter)": 'NA',
"Area": '200'
}
};
jQuery('#btnSubmit').click(function() {
var data = [];
jQuery("#selection").find(':selected').each(function(e) {
var this_input = jQuery(this);
if (this_input.is(':selected')) {
data.push(this_input.val());
}
});
$('#divResult').empty().append(PrintTable(data));
jQuery(document).ready(function ($) {
jQuery('#divResult table tbody tr').find("td:first").each(function ($) {
jQuery(this).addClass(((this.textContent).split(" ").join("").replace('#','').replace(/[()]/g, '')).replace(/ /g, ''));
jQuery(this).siblings('td').addClass(((this.textContent).split(" ").join("").replace('#','').replace(/[()]/g, '')).replace(/ /g, ''));
jQuery(this).parent('tr').addClass(((this.textContent).split(" ").join("").replace('#','').replace(/[()]/g, '')).replace(/ /g, ''));
});
jQuery('.divResult table th:not(:first)').each(function ($) {
jQuery(this).addClass(jQuery(this).text().split(" ").join(""));
jQuery(this).attr("name", this.textContent.split(" ").join(""));
});
jQuery('.divResult table th:first-child').removeClass;
jQuery('.divResult table th:first-child').removeAttr('name');
jQuery('table thead th[class]').each(function () {
$('table tbody td:nth-child(' + ($(this).index() + 1) + ')').addClass(this.className)
});
jQuery(document).ready(function ($) {
var data = [];
jQuery('#divResult table thead th:not(:first)').each(function () {
data.push(jQuery(this).text());
function Column(data) {
var html='';
jQuery.each(data, function(index, value){
html += '<option selected name="' + value + '" class="' + value.split(" ").join("").replace('#','').replace(/[()]/g, '').replace(/ /g, '') + '" >' + value + '</option>'
});
return html;
}
jQuery('#ColumnCheckbox').empty().append(Column(data));
});
});
jQuery('#FilterDiv').show();
$("#ColumnCheckbox").change(function() {
var options = $(this).find("option");
var OptionSelected = $(this).find("option").prop("selected");
$.each(options,function(i,val){
var selected = $(this).prop("selected");
var currentClass = $(this).attr("class");
if(selected == false){
$("table.CompTable thead tr th." + currentClass).hide();
$("table.CompTable tbody tr td." + currentClass).hide();
}else{
$("table.CompTable thead tr th." + currentClass).show();
$("table.CompTable tbody tr td." + currentClass).show();
}
});
});
jQuery(document).ready(function ($) {
var OptionSelected = $("#ColumnCheckbox option:selected").length;
console.log(OptionSelected);
});
jQuery(document).ready(function ($) {
var ColumnsSelected = $("table.CompTable thead > tr > th:not(:first)").length;
console.log(ColumnsSelected);
});
});
});
function PrintTable(data) {
var html = '<table id="CompTable" class="CompTable"><thead><tr>';
if (data && data.length) {
html += '<th> </th>';
jQuery.each(data, function(k, v) {
html += '<th>' + v + '</th>';
});
html += '</tr></thead>';
html += '<tbody>';
jQuery.each(StatJSON[data[0]], function(k, v) {
html += '<tr><td>' + k + '</td>';
jQuery.each(data, function(k2, v2) {
html += '<td>' + StatJSON[data[k2]][k] + '</td>';
});
html += '</tr>';
});
} else { html += 'No results found</td></tr>'; }
html += '</table>';
return html;
}
});
jQuery(function($) {
$.fn.select2.amd.require([
'select2/selection/single',
'select2/selection/placeholder',
'select2/selection/allowClear',
'select2/dropdown',
'select2/dropdown/search',
'select2/dropdown/attachBody',
'select2/utils'
], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {
var SelectionAdapter = Utils.Decorate(
SingleSelection,
Placeholder
);
SelectionAdapter = Utils.Decorate(
SelectionAdapter,
AllowClear
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
DropdownSearch
),
AttachBody
);
var ColumnSelected = $('#ColumnCheckbox')
$(ColumnSelected).select2({
width: '40%',
placeholder: 'Select multiple items',
selectionAdapter: SelectionAdapter,
dropdownAdapter: DropdownAdapter,
allowClear: true,
templateResult: function (data) {
if (!data.id) { return data.text; }
var $res = $('<div></div>');
$res.text(data.text);
$res.addClass('wrap');
return $res;
},
templateSelection: function (data) {
if (!data.id) { return data.text; }
var ColumnselectedNumber = ($(ColumnSelected).val() || []).length;
var ColumnSelectedElements = $(ColumnSelected).val();
var total = $('option', $(ColumnSelected)).length;
return "Selected " + ColumnselectedNumber + " of " + total;
}
});
});
});
.CompTable {
table-layout: fixed;
width: 50%;
position: relative;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
margin: 10px;
border: 1px solid #222;
text-align: center;
}
.select2-results__option .wrap:before{
font-family:fontAwesome;
color:#999;
content:"\f096";
width:25px;
height:25px;
padding-right: 10px;
}
.select2-results__option[aria-selected=true] .wrap:before{
content:"\f14a";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
Options:
<select id="selection" select class="js-example-basic-multiple" multiple="multiple">
<option value="Samsung">Samsung</option>
<option value="Mi">Mi</option>
<option value="Apple">Apple</option>
<option value="LG">LG</option>
</select>
<br /><br />
<input id="btnSubmit" class="button" type="submit" value="submit"/>
<br /><br />
<div id="FilterDiv" style="display: none;">
<select multiple id="ColumnCheckbox"></select>
</div>
<div id="divResult" class="divResult"></div>