I'm using tables of MDL lib. https://getmdl.io/components/index.html#tables-section
But there are no docs how I can retrieve checked values about.
I found only this solution, but this not helping at all:
var checkboxes = document.getElementById('team-table-id')
.querySelector('tbody').querySelectorAll('.mdl-checkbox__input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function() {
console.log(this)
// returns <input type="checkbox" class="mdl-checkbox__input">
// how can I assign and retrieve value to/from this input?
});
}
How can I assign a value to checkbox/input of table rows at all?
How can I retrieve single checked values?
How can I handle "select all" event and get data of all rows?
Ok, I didn't find solution.
So I make my own for temporary:
1) Assign some class for tr's, so it can be found when check event happend
2) assign value for tr's. It can be serialized values or smth like that
3) listen check event and get data
Markup:
<table id="team-table-id" width="100%" class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
<thead>
<tr class="row-info" data-value="all">
<th class="mdl-data-table__cell--non-numeric">Donation Invoice</th>
<th>Donation Name</th>
<th>Donation price</th>
</tr>
</thead>
<tbody>
<tr class="row-info" data-value="one more value">
<td class="mdl-data-table__cell--non-numeric">I-20170419120440</td>
<td>Some Donation Name</td>
<td>$2.90</td>
</tr>
<tr class="row-info" data-value="another value">
<td class="mdl-data-table__cell--non-numeric">C-20170419120454</td>
<td>Anothre</td>
<td>$1.25</td>
</tr>
<!--etc...-->
Javascript:
window.findAncestor = (el, cls) => {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
let checkboxes = document.getElementById('team-table-id')
.querySelectorAll('.mdl-checkbox__input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function() {
console.log(findAncestor(this, 'row-info'))
});
// Returns parent table row, so you can get selected data.
// For example <tr data-value="some value" class="row-info">....
Please, feel free to suggest right one.
UPD:
This approach dnt have bugs and can hanlde all checked values, so I've marked this as "solved".
Have a look at https://github.com/google/material-design-lite/issues/1210 where several solutions (work-around) are presented depending on the version of MDL
I am following this (work-around)
On window.onload I am adding onclick attribute to all checkbox to call function getCheckValue(this), this function traverse through dom to get innerHTML of each td in tr
window.onload=function(){
var checkAll=document.getElementsByClassName('mdl-checkbox__input')
for(var i=0;i<checkAll.length;i++){
checkAll[i].setAttribute('onclick','getCheckValue(this)')
}
}
function getCheckValue(obj){
if(obj.checked){
/*th is checked in thead*/
if(obj.parentElement.parentElement.parentElement.parentElement.nodeName=='THEAD'){
var trs=obj.parentElement.parentElement.parentElement.parentElement.nextElementSibling.children
for(var i=0;i<trs.length;i++){
var tds=trs[i].getElementsByTagName('td')
for(var j=1;j<tds.length;j++){
console.log(tds[j].innerHTML)
}
}
}
else{
/*td inside tbody is checked*/
var tds=obj.parentElement.parentElement.parentElement.getElementsByTagName('td')
for(var i=1;i<tds.length;i++){
console.log(tds[i].innerHTML)
}
}
}else{
/* uncheck th checkbox of thead*/
if(obj.parentElement.parentElement.parentElement.parentElement.nodeName!='THEAD'){
obj.parentElement.parentElement.parentElement.parentElement.previousElementSibling.firstElementChild.firstElementChild.firstElementChild.classList.remove('is-checked')
obj.parentElement.parentElement.parentElement.parentElement.previousElementSibling.firstElementChild.firstElementChild.firstElementChild.firstElementChild.checked=false
}
}
}
Plunker link for demonstration
Related
I came across a problem whose solution has led me to post it here so others may make use of it or improvise better than me.
My Problem: I have a table of results with check boxes to select rows. The requirement was to know if I was selecting(using the checkboxes) the same set of one particular column value, if so I had to do something.
HTML code
Considering the below being my html code for the dynamic table(CFML). The tag has to be inside a loop to dynamically create the table content.
<table class="fixedTable">
<thead class="containerbg">
<tr class="listingheader">
<td>StagingID</td>
<td>BatchID</td>
<td>AuditID</td>
<td>Action</td>
<td>File Name</td>
<td>Card No</td>
<td>Card No</td>
</tr>
</thead>
<tbody>
<tr class="cur_row" >
<td>#staging_id#</td>
<td>#batch_import_job_id#</td>
<td>#audit_Id#</td>
<td>#code#</td>
<td class="file_name">#source_filename#</td>
<td>#card_number#</td>
<td class="tblResolve">
<input type="checkbox" class="checkBoxClass cb" name="resolveErrorsCheck" value="#row_no#">
</td>
</tr>
JS Code
//register the click event
$(document).ready(function() {
$(document).on('click', '.cb',enableDisableActions);
});
function enableDisableActions() {
var values = new Array();
$.each($("input[name='resolveErrorsCheck']:checked").closest('td').siblings('.file_name'),
function (){
values.push($(this).text());
});
const initial = values[0];
const result = values.filter(src => src != initial);
if(result.length){
//no duplicate file_name selected
//do something
}else{
//duplicate file_name selected
//do something
}
}
I have a table with a checkbox in the table header, which will be used to toggle all the checkboxes below it. I've add a JavaScript function to the checkbox in the header, but so far it only selects the top checkbox (one checkbox) instead of all of them. Any suggestions or advice on what I've done wrong or what to research?
HTML table header code:
<thead>
<tr>
<th><center><input type="checkbox" value="" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"></center></th>
<th>Sender</th>
<th>Receiver</th>
<th>Subject</th>
<th>Date</th>
</tr>
</thead>
PHP table code:
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_1" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Javascript code:
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = document.getElementById(cbarray[i].id);
cb.checked = master.checked;
}
}
The problem is you setting the same ID (cb1_1) to all the checkboxes (which is invalid in HTML) Id should be unique in the page. Thus, it only select the first found checkbox and discard the rest. To resolve this give unique ids to checkboxes.
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_'.$pmid.'" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Note: I just use the $pmid just as an example you should use appropriate value as per your scenario
I see 2 issues with you code.
(Probably) using the same id for multiple DOM elements
Your PHP code suggests that you are probably using a loop to create the checkboxes but you are using the same id for all of them "cb1_1".
Same as #atul here.
Improperly selecting your checkbox elements
Since you are using the same id for all inputs,
var cb = document.getElementById(cbarray[i].id);always returns the same element. A way to solve it is to use the solution provided by #atul
Another way is to rewrite your javascript as follows :
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = cbarray[i];
cb.checked = master.checked;
}
}
Your cbarray is already your checkboxes array, so it is redundant (aka useless) to call document.getElementById(cbarray[i].id) to get the element when you already have it with cbarray[i].
Iam completely confused at a point and need anyone's help here. Went through various examples but nothing could help.
I have a created dynamic table, added with checkboxes. Now whenever a row is selected its id will be bound to an array and it will be diplayed at the top of table.
What I need is:The code for functionality of select all check box. And whenever all the rows are selected by select all checkbox, its ids has to be displayed.
Below is the code for the table:
<table>
<thead>
<tr>
<th>
<input name="all"
type="checkbox"
ng-click="selectAll()" />
</th>
<th>ID</th>
<th>Date</th>
</tr>
</thead>
<tbody ng-repeat="x in cons">
<tr>
<td>
<input type="checkbox"
name="selectedids[]"
value="{{x.id}}"
ng-checked="idSelection.indexOf(x.id) > -1"
ng-click="toggleSelection(x.id, idSelection)"> </td>
<td>{{x.id}}</td>
<td>{{x.title}}</td>
</tr>
</tbody>
app.js:
$scope.idSelection = [];
$scope.toggleSelection = function toggleSelection(selectionName, listSelection) {
var idx = listSelection.indexOf(selectionName);
// is currently selected
if (idx > -1) {
listSelection.splice(idx, 1);
}
// is newly selected
else {
listSelection.push(selectionName);
}
};
//$scope.selectAll=function(){}
//Need code for this function to work
Here is a demo: http://plnkr.co/edit/m9eQeXRMwzRdfCUi5YpX?p=preview.
Will be grateful, if anyone can guide.
You need a variable to keep track of whether 'All' is currently active or not. If not, we create a new array of all item id's using the array map function, and pass this to idSelection. If allSelected is currently active, we pass an empty array to idSelection
$scope.allSelected = false;
$scope.selectAll = function() {
$scope.allSelected = !$scope.allSelected;
if($scope.allSelected) {
$scope.idSelection = $scope.cons.map(function(item) {
return item.id;
});
} else {
$scope.idSelection = [];
}
}
I have dynamic table that has table cell with checkbox field. This fields are populated from DB so my table is dynamic. I would like to loop through checkboxes based on their class name. In that loop I want to check value for each check box. For example if value is equal 1 I want checkbox to be checked, if not unchecked. Alo I'm not sure if possible but I would like to set unique ID for each of these check boxes. Since my table is dynamic my fields need to have unique ID's. Here is example of my code:
<table>
<thead>
<tr>
<th>#</th>
<th>Time Slots</th>
<th>Block</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>~(SLOT_LABEL)</td>
<td>
<span>
<input type="checkbox" name="CF-[Events]" class="block" id="block_"+Value that will make this ID unique. value="~(SLOT_ID)"/>
</span>
</td>
</tr>
</tbody>
</table>
Also in current language that I work with to read values from DB I have to use NAME tag. If anyone can help please let me know. Thank you.
You can use the attribute selector to retrieve elements by both their name and value. Try this:
$('input[name="CF-[Events]"][value="1"]').prop("checked", true);
Working example
If you don't want a jQuery solution, it is also possible to fetch these elements with the querySelector:
var inputs = document.querySelectorAll("input.block");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
you can do it in jquery by each loop
$('.ClassName').each(function(i, o) {
// o is object in your case checkbox
// i is index
// your code
});
$("input[name='CF-[Events]']").each(function() {
if($(this).val() === "1")
{
$(this).prop("checked", true);
}
});
My javascript code for filtering is not working on Swedish letters å ä ö
<input name='tablefilter' type='checkbox' value='Linköping' id='tablefilter1' checked/>
<label for='tablefilter1'>Linköping</label>
<input name='tablefilter' type='checkbox' value='Mjölby' id='tablefilter2' checked/>
<label for='tablefilter2'>Mjölby</label>
<input name='tablefilter' type='checkbox' value='Norrköping' id='tablefilter3' checked/>
<label for='tablefilter3'>Norrköping</label>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody id='tablebody'>
<tr>
<td>Linköping</td>
<td>One</td>
<td>First</td>
</tr>
<tr>
<td>Mjölby</td>
<td>Two</td>
<td>Second</td>
</tr>
<tr>
<td>Norrköping</td>
<td>Three</td>
<td>Third</td>
</tr>
</tbody>
</table>
js
/* Demo filtering table using checkboxes. Filters against first td value */
/* Set 'ready' handler' */
document.addEventListener('DOMContentLoaded', initFunc);
/* When document ready, set click handlers for the filter boxes */
function initFunc(event) {
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
filters[i].addEventListener('click', buildAndExecFilter);
}
}
/*
This function gets called when clicking on table filter checkboxes.
It builds a list of selected values and then filters the table based on that
*/
function buildAndExecFilter() {
var show = [];
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
if (filters[i].checked) {
show.push(filters[i].value);
}
}
execFilter(show); // Filter based on selected values
}
function execFilter(show) {
/* For all rows of table, see if td 0 contains a selected value to filter */
var rows = document.getElementById('tablebody').getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
var display = ""; // Default to display
// If it is not found in the selected filter values, don't show it
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
// Update the display accordingly
rows[i].style.display = display;
}
}
http://jsfiddle.net/2Lm7pytt/4/
It works on jsfiddle, but it's not working on my visual studio. The problem is not that it can't display Swedish letters, because it can.
The problem is that the JavaScript is not working on Swedish letters.
What should I do to make it work?
you might try adding to the top of the head tag
< meta charset="utf-8" />
This could fail at several points but it is most likely failing on the comparison due to an encoding issue, so I would suggest using the debugger to breakpoint the JavaScript before this line:
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
Check what is contained within textContent, try doing a comparison in your Immediate Window, e.g. rows[i].children[0].textContent === "Linköping". If you find this coming back false, this will likely confirm it.
Go to FILE > Advanced Save Options in Visual Studio and check the encoding option set here - I am using "Unicode (UTF-8 with signature) - Codepage 65001" and my code includes the meta code as seen in Brandon's suggestion in the answers below. With these set, it is running as intended, for me.