Get sibling td values based on all checked checkboxes in a datatable? - javascript

$('#save-board-assignees').click(function ()
{
$('#board_assignee_table_wrapper input[type="checkbox"]:checked').each(function(i, td_e)
{
console.log('Found checked checkbox');
var assignee_id = 0;
var team_id = 0;
var assignee_holder = [];
assignee_id = $(this).closest('td').next().attr('id');
assignee_name = $(this).closest('td').next().html();
team_id = $(this).closest('td').next().next().attr('id');
console.log('Assignee name: ' + assignee_name);
console.log('Team id: ' + team_id);
console.log('Assignee id: ' + assignee_id);
assignee_holder.push(assignee_id, assignee_name);
board_assignees.push(assignee_holder);
});
}
This code only gets the values of the sibling <td> (Assignee name, team id, assignee id) of the checked checkbox on the page selected. It doesn't pick up the checked checkboxes in the other pages of the DataTable.
Here's a sample snippet of the table structure:
https://jsfiddle.net/30u4knrs/

Use .$() (https://datatables.net/reference/api/%24()) to access all table elements (not just those currently visible):
var table = $('#example').DataTable();
table
.$('input[type="checkbox"]:checked')
.each(function(i, td_e) { ...

Related

Check if KendoGrid selected checkbox is checked or not

I have a ASP.Net MVC Kendo Grid with checkbox selection, as the documentation I added the checkbox using columns.Select().Width(50); as, then I want to fill an array of selected checkboxes inside of onChange function with javascript as:
Note: the stations array already have some values I.E [1,2,3], so I want to add new values in the next script
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
stations.push(grid.dataItem(this).StationId);
})
}
The problem is on each check it is adding all existing checked checkboxes, I have no way to do something like if(checkbox is not checked) do a pop instead a push.
How can I check if clicked checkbox is checked or not in order to implement push or pop logic?
The select method will return all rows that are currently selected. If you need to figure out which is the checkbox that the user clicked last, you can probably toggle a class when the checkbox is checked/unchecked
function onChange(e) {
const grid = e.sender;
var items = grid.items();
let ids = '';
grid.select().each(function(idx,itm) {
$(itm).find("input").hasClass("checkedFlag") ?
kendoConsole.log(grid.dataItem(itm).ProductName + " was checked") :
kendoConsole.log(grid.dataItem(itm).ProductName + " was NOT checked");
})
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
kendoConsole.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
}
function onDataBound(arg) {
$("input.k-select-checkbox").change(function(){
$(this).toggleClass("checkedFlag")
})
kendoConsole.log("Grid data bound");
}
If you are interested in only the Id's of the selected items then the Grid exposes a selectedKeyNames method, that you could use instead.
The change event of the Kendo grid will fire when the user selects or deselects a table row or cell in the grid (documentation), but it does not provide us with which rows are selected or deselected.
What you will need to do is store the selected items outside of the grid, compare it to the results of the select method in the change event, then store the updated results.
Something along these lines:
var selectedRecords = [];
function onChange(e) {
var updatedSelectedRecords = e.sender.select();
if (selectedRecords) {
var recordsSelected = updatedSelectedRecords.filter(record => !selectedRecords.includes(record)).map(record => record.StationId.toString());
stations.push(...recordsSelected);
var recordsDeselected = selectedRecords.filter(record => !updatedSelectedRecords.includes(record));
// do something with deselected records?
}
selectedRecords = updatedSelectedRecords;
}

How to select the particular list box item using Jquery?

I want to select one of the list box item when user select the table row.
The last item user added SupplierCode to a table by clicking ADD Button. When user want to modify the records from table, once they click that particular row, the value should move to FilterValue and Field in the list box should select that particular Field Name which is selected by user.
Now user select the first row to modify the value. That value is moved to FilterValue textbox, But list box item is not selected automatically to StoreID
But when I check the code in browser. it shows selected for that particular item which item user wants to select, but the color is not changed.
This is my code
Jquery code
//SELECT Table ROW
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
var FieldName = tr.find("td:first").text();
var Values = tr.find("td:last").text();
FieldName = FieldName.replace('AND ', '');
FieldName = FieldName.replace('OR ', '');
Values = Values.replace('IN(', '');
Values = Values.replace(')', '');
alert(FieldName + ' ' + Values);
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#txtFilterValue").val(Values);
});
try with following code and check if it works
//SELECT Table ROW
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
var FieldName = tr.find("td:first").text();
var Values = tr.find("td:last").text();
FieldName = FieldName.replace('AND ', '');
FieldName = FieldName.replace('OR ', '');
Values = Values.replace('IN(', '');
Values = Values.replace(')', '');
//alert(FieldName + ' ' + Values); provided your FieldName as correct value
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values);
});

Select unselect checkboxes using jquery

I have a list of checkboxes in my kendo grid.Select all option is also there.
Problem is When i click select all then all the checkboxes selected and then unselect some checkboxes and going to save then it shows me all the checkboxes.(un checked checkboxes also shown )
My Code
$('#itemGrid').on('change', '.usedchk', function () {
var checked = $(this).is(':checked');
var grid = $('#itemGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
var selected = $('#selected').val();
var id = dataItem.itemId;
if ($('#selected').val().indexOf(id) == -1) {
if ($('#selected').val() == '') {
$('#selected').val(id);
} else {
$('#selected').val(selected + "," + id );
}
}
});
use below code on save, to get all checked checkboxes as a comma separated string
var output = $.map($('#selected:checked'), function(n, i){
return n.value;
}).join(',');

link a checkbox to an object in Javascript

Suppose I have a table which is populated by filling out a form on a page and clicking the submit button.
The last column of the table is a Completed section with a checkbox on each row. On clicking on the checkbox I want to change the .completed property from false to true on that object.
How can I distinguish which checkbox was clicked and change the property from that row?
this.addRowToTable = function() {
return "<tr id='tableRow'><td>" + this.app + "</td><td>" + this.priority + "</td><td>" + this.date + "</td><td>" + this.additionalNotes + "</td><td>" + "<input type='checkbox' class='checkApp[]' value='" + this.completed + "' />" + "</td></tr>";
};
I have all the checkboxes in the checkApp array, but Im not sure where to go from there?.
This is called when the form is submitted:
function addAppointment() {
if (txtApp.value == "" || txtPriority.value == "" || txtDate.value == "" || {
alert("Please fill all text fields");
} else {
var app = new Appointment(txtApp.value, txtPriority.value, txtDate.value, txtNotes.value, false);
apps.push(app);
localStorage.setItem("apps", JSON.stringify(apps));
clearUI();
}
updateTable();
updateTable() loops through all objects in my array and adds them between table tags:
for (var i = 0; i < apps.length; i++) {
var app = new Appointment(apps[i].app, apps[i].priority, expenses[i].date, apps[i].notes, false);
tblHTML += app.addRowToTable();
}
My Appointment Object:
function Appointment(app, priority, date, notes, completed) {
this.app = app;
this.priority = priority;
this.date = date;
this.additionalNotes = notes;
this.completed = completed;
this.addRowToTable = function { ... };
}
First of all, in HTML, id attributes should be unique. So, make sure table rows have unique IDs. At the moment, all of them have the identical ID of tableRow.
Besides, you should consider using a framework/library such as jQuery for real-world scenarios rather than creating the DOM elements, etc. manually.
Now back to the original problem: if you use the DOM API rather than string concatenation to create the table rows, you can add custom fields to the DOM objects representing the table rows. So, from each table row, you can have a reference back to its corresponding Appointment object:
var row = document.createElement("tr");
row.appointment = this;
Similarly, you can use the DOM API to create the table cells as well as the checkbox:
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
where addTd is the following function:
function addTd(row, innerHTML) {
var td = document.createElement("td");
td.innerHTML = innerHTML;
row.appendChild(td);
}
Now that you are using the DOM APIs, you can easily attach event listeners to each checkbox object as well.
Then inside the event listener you can get a reference back to the Appointment corresponding to the row you
have changed its checkbox:
var row = document.createElement("tr");
row.appointment = this;
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
input.addEventListener("change", function(event) {
var row = this.parentNode.parentNode,
appointment = row.appointment;
// change appointment however you like
});

jQuery - Get table cell value

I have a table which looks like the following. The price normally comes from a database this is just for showing the problem I have.
$(document).ready(function() {
$(document).delegate('.amount input[type="text"]','keyup',(function() {
var $this = $(this);
var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();
var amount = $this.val();
alert(price);
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" name="tickets" id="tickets" class="amount" maxlength="2" autocomplete="off"></td>
<td>Ticket:</td>
<td class="price">20,50</td>
<td class="sub_total"></td>
</tr>
</table>
What I would like to do is: when the user types a number in the field tickets it should update the field sub_total. With the jQuery I have this is not working. When I alert(price) I get undefined. So I wonder how to make the sub_total field with auto updated values. It might also be interesting to know that I have more rows like this beneath this row. So the script should only update the field from one specific row at a time.
What I already tried but without success:
How to get a table cell value using jQuery;
How to get a table cell value using jQuery?;
How to get table cell values any where in the table using jquery
Thanks in advance.
You need to do traverse back up to the parent tr element before you try to find the .sub_title or .price elements.
$(document).ready(function() {
$(document).delegate('.amount input[type="text"]','keyup',(function() {
var $this = $(this);
var $tr = $this.closest("tr");
var sub_total = $tr.find('.sub_total');
var price = $tr.find('.price').text();
var amount = $this.val();
alert(price);
}));
});
Change you code like this
$(document).ready(function() {
$(document).on('input[type="text"].amount', 'keyup', (function() {
var $this = $(this);
var sub_total = $this.closest("tr").find('.sub_total');
var price = $this.closest("tr").find('.price').text();
var amount = $this.val();
alert(price);
}));
});
find() will search for the children. So you should get into the parent tr first before using find().
You can use closest("tr") to get the parent tr element
It's because price and sub_total are not children of the current element (as find is selecting):
var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();
they are siblings of its parent or more simply children of the container tr.
Try instead:
var sub_total = $this.closest('tr').find('.sub_total');
var price = $this.closest('tr').find('.price').text();
example for a
<table id="#myTable">
I write this:
function setCell( idTab, row, col, text) {
var idCel = idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
$(idCel).html(text);
}
function getCell( idTab, row, col ) {
var idCel =idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
return $(idCel).html();
}
setCell( "#myTab", 3, 4, "new value" );
alert( getCell("#myTab", 3, 4);

Categories

Resources