Datatable row : manually update field - javascript

I have a datatable. I get a set of selected rows.
When i loop through, and update the value of a field remark,
I can't do it.
how do i manually update the value of a specific field in a row?
var table = $('#bankReconDataListing').DataTable();
$.map(table.rows('.selectedrow').data(), function (item) {
item.remarks = 'updated values';
console.log('-----------------1>',item);
});

<table id="bankReconDataListing">
<thead>
<tr>
<td>head</td>
<td>gender</td>
</tr>
</thead>
<tbody>
<tr><td>one</td><td>boy</td></tr>
<tr class="selectedrow"><td>two</td><td>boys</td></tr>
<tr><td>three</td>
<td>boys</td></tr>
</tbody>
</table>
var table = $('#bankReconDataListing').DataTable();
var temp = table.row(2).data();
alert("value before update = " + temp[0]);
temp[0] = "six";
table.row(2).data(temp).draw();
alert("value after update = " + temp[0]);

Related

HTML Table - Loop through dynamically created rows and if field in specific column contains date prevent row from editing

I'm trying to create a JavaScript to disable a row if EndDate contains a date.
The table is generate automatically so I thought to lookup how many rows the table has and start iterating through them. Check if fields in column EndDate contain a date.
If that row contains a date then disable any field in that row.
To track down the fields I used this to check if I could disable them.
document.getElementById("r0_LineItemCode").disabled = "true";
document.getElementById("r0_LineItemCode_ref_ref").disabled = "true";
document.getElementById("pr0_LineItemCode").disabled = "true";
document.getElementById("r0_ec_type").disabled = "true";
I accomplished to loop through the rows and find out how many rows there are and show the data on the console.
But now selecting that field to check if it contains a date and then disable those row items fails.
Code to track down the rows and iterate through the rows:
let text = "";
var endDateFields = [];
var rowData = document.querySelector("#RequestLinesGrid_RowIDs");
console.log(rowData);
console.log(rowData.value);
const rows = rowData.value.split(',');
rows.forEach(myFunction);
console.log(text);
console.log(r0_EndDate);
console.log(r1_EndDate);
console.log(r2_EndDate);
function myFunction(item, index) {
text += "indexNumber = " + index + " variableField: " + item + "_EndDate";
var str = item + "_EndDate";
eval(str);
console.log(str);
}
I have the feeling I'm almost there, but need a little push in the right direction :)
This is a simple logic of your problem, if date is not empty disable all inputs of the parent tr.
document.querySelector('table').querySelectorAll('td.date').forEach(el => {
if (el.innerHTML !== '') {
const parentTr = el.parentElement;
parentTr.querySelectorAll('input').forEach(input => {
input.disabled = true;
});
}
});
<table>
<thead>
<th>id</th>
<th>input1 Example</th>
<th>input2 Example</th>
<th>date Example</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><input name='test' type='text'></td>
<td><input name='test' type='text'></td>
<td class='date'>10/10/2021</td>
</tr>
<tr>
<td>2</td>
<td><input name='test' type='text'></td>
<td><input name='test' type='text'></td>
<td class='date'>10/10/2021</td>
</tr>
<tr>
<td>1</td>
<td><input name='test' type='text'></td>
<td><input name='test' type='text'></td>
<td class='date'></td>
</tr>
</tbody>
</table>
Instead of check all row just add a simple class on td have date then check it as my example.

How to alter table row value which is inserted dynamically using Jquery?

I want to alter HTML Table row which is inserted by dynamically.
At beginning there will no rows in table.
HTML Code
<table class="table table-hover " id="queryTable">
<thead>
<tr>
<th>Field Name</th>
<th>Values</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
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(')', '');
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values); //FilterValue textbox id
});
$("#btnChange").click(function () {
td.text($("#txtFilterValue").val());
});
Those 3 records are added dynamically. When user wants to modify the value of any FieldName of Values ,Once user click that row from the table, the value will show on Filter Value textbox as you can see above.
In the above pic, User select second row. once the user change the value in textbox and when they click the Change button the second row should alter.
Assuming your table id as YOURTABLEID and your textbox id as FILTERVALUETEXTBOX
var td;
$(document).on("click","#YOURTABLEID td",function(){
td=$(this);
$("#FILTERVALUETEXTBOX").val($(this).text());
});
If you want to click on tr and want to get second td value, then
var td;
$(document).on("click","#YOURTABLEID tr",function(){
td=$(this).find("td:last"); //AS SECOND TD IS LAST
$("#FILTERVALUETEXTBOX").val(td.text());
});
Once you get your td value in textbox, Change button click event will be as follow
$("#btnChange").click(function(){
td.text($("#FILTERVALUETEXTBOX").val());
});
UPDATE
var td;//THIS IS MISSING IN YOUR CODE
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
td=$(this).find("td:last");//THIS IS MISSING IN YOUR CODE
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(')', '');
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values); //FilterValue textbox id
});
$("#btnChange").click(function () {
td.text($("#txtFilterValue").val());
});

Loop through a form which contains another form

I want to loop through a form with Javascript but my problem is that I have another form in the first form.
I'd like to loop through the first form only, not the inner one. I found this method on an other post :
var table = $("#table_cultures tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + productId
+ '\nProduct: ' + product
+ '\nQuantity: ' + Quantity);
});
This method works but loop through the both forms.
EDIT 1 :
The html looks like :
<form>
<table>
<tr>
<td>Something here</td>
</tr>
<tr>
<td>
<form>
<table>
//tr td ...
</table>
</form>
</td>
</tr>
</table>
</form>
nesting of <form> elements is not allowed
please see:
https://www.w3.org/TR/html5/forms.html#the-form-element
"...Flow content, but with no form element descendants..."

Get selected drop-down value of a row in html table using JavaScript/jQuery

I have a html table with 4 columns and multiple rows
column1 : simple text
column2 : simple text
column3 : select list with 2 values
column4 : Button that performs some operation
At run time, I want to get the selected / entered values for all the columns of that row against which column4 button is clicked. I know a little of JavaScript/jQuery.
Here is the static table code
<table id="invoiceTbl" border="1">
<thead>
<tr>
<th>Broker info</th>
<th>Receivable Amount</th>
<<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
And I am populating table i.e. inserting data on AJAX call like this:
$.ajax({
type: "POST",
data: $('#searchDetails').serialize(),
async: false,
cache: false,
url: "/opsadmin/search.json",
dataType: 'json',
success: function (result) {
var i = 1;
$.each(result, function (index, value) {
alert(index + ": " + value.brokerInfo);
$('table#invoiceTbl TBODY').append('<tr> <td>' + i + '</td><td>' + value.brokerInfo + '</td><td>' + value.receivableAmount + '</td><td><select name="act" id="s"><option>PENDING</option><option>CLEARED</option></select></td><td><input type="button" value="Process" onclick="updateStatus(\'' + index + '\')"</input></td></tr>');
i++;
});
}
});
return false;
First set the unique ID to each of your "select" with help of index like:
'<select name="act" id="s'+ index +'">'
and pass the index with "updateStatus(index)" function call.
function updateStatus(index) {
$('#s'+index).val(); // value of selected box.
}
$("#invoiceTbl input[type=button]").click(function(e){
$(e.target).closest("tr").find("td").slice(0,2).each(function(){
console.log($(this).text());
});
});
On #button click you will get an array (arr) that holds the values of the clicked row cells:
$('#button').on('click', function() {
var arr = [];
$(this).closest('tr').find('td').each(function() {
var that = $(this);
if (that.find('input[type="text"]').length > 0) {
arr.push(that.find('input[type="text"]').val());
} else if (that.find('select').length > 0) {
arr.push(that.find('select').val());
} else {
arr.push(that.text());
}
});
alert(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>text</td>
<td>text2</td>
<td>
<select>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
</select>
</td>
<td><button id="button">Click</button></td>
</tr>
</tbody>
</table>
There's already a few good answers, but my solution is a bit different:
$("#invoiceTbl tr").each(function(){
var select = $(this).find("select");
var button = $(this).find("button");
button.click(function(){
alert(select.val());
});
});
If you also want the content of the other columns, that's a bit more difficult:
$("#invoiceTbl tr").each(function(){
var tr = $(this);
var button = $(this).find("button");
button.click(function(){
tr.find("td").each(function(){
var select = $(this).find("select");
var td_button = $(this).find("button");
if(!td_button.length)
{
if(select.length)
console.log(select.val());
else
console.log($(this).text());
}
});
});
});
Check out https://jsfiddle.net/cgfjewoe/ to see it run.

Jquery group by td with same class

I have the current table data:
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr>
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed)
and I've coded the current javascript:
$(".groupWrapper").each(function() {
var total = 0;
$(this).find(".td2").each(function() {
total += parseInt($(this).text());
});
$(this).append($("<td></td>").text('Total: ' + total));
});
by the way the current java scripr doesn't groupby.
Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
</tr class="Violão"> This doesn't make sense. You only close the tag: </tr>. And I'm assuming you know that since the rest of your code is proper (except for your classnames. Check this question out).
If you want to add the values of each <td> with a class of td2, see below.
Try this jQuery:
var sum = 0;
$(".td2").each(function(){
sum = sum + $(this).text();
});
This should add each number within the tds to the variable sum.
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr class="Violão">
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
var dictionary = {};
$("td").each(function(){
if(!dictionary[$(this).attr("class"))
dictionary[$(this).attr("class")] = 0;
dictionary[$(this).attr("class")] += parseInt($(this).html());
});
// declare an array to hold unique class names
var dictionary = [];
// Cycle through the table rows
$("table tr").each(function() {
var thisName = $(this).attr("class");
// Add them to the array if they aren't in it.
if ($.inArray(thisName, dictionary) == -1) {
dictionary.push(thisName);
}
});
// Cycle through the array
for(var obj in dictionary) {
var className = dictionary[obj];
var total = 0;
// Cycle through all tr's with the current class, get the amount from each, add them to the total
$("table tr." + className).each(function() {
total += parseInt($(this).children(".td2").text());
});
// Append a td with the total.
$("table tr." + className).append("<td>Total: " + total + "</td>");
}
Fiddler (on the roof): http://jsfiddle.net/ABRsj/
assuming the tr only has one class given!
var sums = [];
$('.td2').each(function(){
var val = $(this).text();
var parentClass = $(this).parent().attr('class');
if(sums[parentClass] != undefined) sums[parentClass] +=parseFloat(val);
else sums[parentClass] = parseFloat(val);
});
for(var key in sums){
$('<tr><td>Total ('+key+')</td><td>'+sums[key]+'</td></tr>').appendTo($('table'));
}
I would give the table some ID and change to appendTo($('#<thID>'))
The solution:
http://jsfiddle.net/sLysV/2/
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient.
Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below
http://jsfiddle.net/Phunky/Vng7F/
But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.

Categories

Resources