how can i add each value entered in my TD using javascript? - javascript

i have a list of rows and columns. basically the first_value and second_value column is an input type where the user can enter and the total column is a span. how can i add the first_value and second_value column to its specific row?
ID| first_value | second value | total
1 0 50 50
2 20 0 20
3 10 0 10
4 20 10 30
5 10 0 10
here is my html/php code
<table class="table table-striped" id="user_set_goal_table" width="100%">
<thead>
<tr>
<th>#</th>
<th>First_value</th>
<th>Second_value</th>
<th>total</th>
</thead>
<tbody>
for($i=1;$i<=16;$i++){
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo "<input type='text' class='navigate_TD_ID' id='first_value".$i."' "; ?></td>
<td><?php echo "<input type='text' class='navigate_TD_ID' id='second_value".$i."' "; ?></td>
<td><?php echo "<span id='total".$i." '></span>"?></td>
</tr>
<?php
}
</tbody>
javascript code:
$('.navigate_TD_ID').on('change', function() {
var input_id = $(this).attr('id');
alert(input_id);
});
i can already get which id the user click on TD but i dont know how will i implement this calculations, i mean how can i calculate and display to its specific position in row. any help would be really appreciated.

To achieve this you can use jQuery's DOM traversal methods to find the span relative to the input that raised the event. Specifically, use the this reference along with closest() and find().
Also note that it's better practice to use common classes on repeated content, instead of generating dynamic id attributes. Try this:
$('.first, .second').on('input', function() {
var $tr = $(this).closest('tr');
var f = parseFloat($tr.find('.first').val()) || 0;
var s = parseFloat($tr.find('.second').val()) || 0;
$tr.find('.total').text(f + s);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="user_set_goal_table" width="100%">
<thead>
<tr>
<th>#</th>
<th>First_value</th>
<th>Second_value</th>
<th>total</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><input type="text" class="navigate first" /></td>
<td><input type="text" class="navigate second" /></td>
<td><span class="total"></span></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" class="navigate first" /></td>
<td><input type="text" class="navigate second" /></td>
<td><span class="total"></span></td>
</tr>
</tbody>
</table>

Quick example with vanilla js and without PHP
<table class="table table-striped" id="user_set_goal_table" width="50%">
<thead style="text-align:left;">
<tr>
<th>#</th>
<th>First_value</th>
<th>Second_value</th>
<th>total</th>
</thead>
<tbody>
</tbody>
</table>
<script>
// table body
let tbody = document.querySelectorAll('table tbody')[0];
// trs
let rows = tbody.children;
// fill table body
for(let j = 0; j < 16; j++)
{
tbody.innerHTML += `
<td>${j}</td>
<td><input type="text" class="first"></td>
<td><input type="text" class="second"></td>
<td><span></span></td>
`;
}
for(let i = 0; i < rows.length; i++)
{
let firstInput = rows[i].children[1].firstElementChild;
let secondInput = rows[i].children[2].firstElementChild;
let total = rows[i].children[3].firstElementChild;
[firstInput, secondInput].forEach((elem) => {
elem.addEventListener('input' ,(e) => {
let first = e.target.value;
let second = (e.target.className == "first") ? secondInput.value : firstInput.value;
total.innerText = parseFloat(first) + parseFloat(second);
});
});
}
Result:

Related

make each table value display in each textbox

I have this html table and 2 textboxes:
<table id="myTbl">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
<input type="text" name="txt" id="txt" >
<input type="text" name="txt" id="txt2" >
I want when reload the page, the values 1 and 2 must display in each textbox. How can I do it?
I have tried this js code but wrong and I want it auto display, not to click it:
var cells = document.querySelectorAll('#myTbl tbody ');
Array.from(cells).forEach(function (elem) {
elem.addEventListener('click', function () {
document.getElementById('txt').value = this.textContent;
})
})
var tbody = document.getElementsByTagName('tbody')[0]
var input1 = document.getElementById('txt')
var input2 = document.getElementById('txt2')
input1.value = tbody.getElementsByTagName('td')[0].textContent
input2.value = tbody.getElementsByTagName('td')[1].textContent

Change color of text in row by checkbox in same row in table

I am creating a very simple table having two columns 1.Text 2.Checkbox. i want that whenever i make the checkbox checked corresponding row's text color should be changed. i don't know how to do that.can anyone guide please?
i tried this way but didn't work. here's the code:
<?php
$var=1;
$cbid = "chechbox".$var;
echo"<table>
<tr>
<th>Text</th>
<th>Checkbox</th>
</tr>";
while($var<=3){
echo"
<tr>
<td>
<input type='text' id='$var' value='$var'>
</td>
<td>
<input type='checkbox' id='$cbid' onclick='fun()'>
</td>
</tr>
</table>
<script>
function fun(){
var a = document.getElementById($var);
var b = document.getElemeentById($cbid);
if(b.checked == true){
a.style.color='red';
}
}
</script>
";
$var++;
$cbid = 'chechbox'.$var;
}
?>
i am beginner. i am not even sure if i can make multiple script using while loop.
You can do so:
document.getElementById('check').onchange = function () {
let textVar = document.getElementById('tableText');
if (document.getElementById('check').checked) {
textVar.style.color = 'red';
} else {
textVar.style.color = 'green';
}
}
<table>
<tr>
<th>Text</th>
<th>Checkbox</th>
</tr>
<tr>
<td><input type='checkbox' id='check' value='$var'></td>
<td><input type='text' id='tableText' value='$var'></td>
</tr>
</table>

how to get dynamically generated table td input value

I have a dynamically generated table like below
this is the code that generate this table
function pullInventory(data) {
var container = document.getElementById('inventoryContainer')
var index = 0;
console.log(index)
data.forEach(function(awardsSnap) {
index ++;
// console.log(awardsSnap, index)
var awardItem = awardsSnap.val()
// Attach an asynchronous callback to rea
var NSNcard = `
<tr>
<td class="serial">${awardItem.NSN}</td>
<td> ${awardItem.Nomenclature} </td>
<td> ${awardItem.Awarddate} </td>
<td> ${awardItem.Awardid} </td>
<td>
<input type="text" placeholder="i.e. 100 EA" class="form-control" value="" id="qty${index}"style="width: 110px;">
</td>
<td>
<input type="text" placeholder="i.e. $9.23 " class="form-control" value="" style="width: 110px;">
</td>
</tr>
`;
container.innerHTML += NSNcard;
});
}
I want to get all the user entered quantity and price on a button click so I use this
document.querySelector("#savebtn").addEventListener("click", e => {
var rows = document.getElementById("WelcomeTable").getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;
saveInventory(rows);
});
function saveInventory(rows) {
const columnHeader = Array.prototype.map.call(
document.querySelectorAll(".table th"),
th => {
return th.innerHTML;
}
);
const tableContent = Object.values(
document.querySelectorAll(".table tbody tr")
).map(tr => {
const tableRow = Object.values(tr.querySelectorAll("td")).reduce(
(accum, curr, i) => {
const obj = { ...accum };
obj[columnHeader[i]] = curr.innerHTML.trim();
console.log(accum, curr, i)
return obj;
},
{}
);
return tableRow;
});
}
everything works fine except that the two input column in the table above does not detect user input. I'm not able to get the quantity and price value entered.
Award Date: "08-23-2012"
Award#: "SP452013D0055"
NSN: "S222V00004789"
Nomenclature: " BATTERIES, NICKEL-CADMIUM"
Quantity: "<input type="text" placeholder="i.e. 100 EA" class="form-control" value="" id="qty18" style="width: 110px;">"
Unit-Price: "<input type="text" placeholder="i.e. $9.23 " class="form-control" value="" style="width: 110px;">"
I tried this and other things but they output undefine
obj[columnHeader[4]]=curr.val();
obj[columnHeader[4]]=curr.value;
how could i get the enetered quantity and price from the dynamic table?
You could try doing something like this:
window.onload = ()=>{
let targetTable = document.getElementById('target-table');
let targetTableRows = targetTable.rows;
let tableHeaders = targetTableRows[0];
// start from the second row as the first one only contains the table's headers
for(let i = 1; i < targetTableRows.length; i++){
// loop over the contents of each row
for(let j = 0; j < targetTableRows[i].cells.length; j++){
// something we could use to identify a given item
let currColumn = tableHeaders.cells[j].innerHTML;
// the current <td> element
let currData = targetTableRows[i].cells[j];
// the input field in the row
let currDataInput = currData.querySelector('input');
// is the current <td> element containing an input field? print its value.
// Otherwise, print whatever is insside
currDataInput ? console.log(`${currColumn}: ${currDataInput.value}`)
: console.log(`${currColumn}: ${currData.innerHTML}`);
}
}
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table" id="target-table">
<thead>
<tr>
<th scope="col">Person #</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
<td><input type="text" value="01-quantity" id="value-01"></td>
<td><input type="text" value="01-price" id="value-01-2"></td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
<td><input type="text" value="02-quantity" id="value-02"></td>
<td><input type="text" value="02-price" id="value-02-2"></td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
<td><input type="text" value="03-quantity" id="value-03"></td>
<td><input type="text" value="03-price" id="value-03-2"></td>
</tr>
</tbody>
</table>
What is done in the example above should also work for your specific case.
Also, here's a working exmaple :)
val() is jQuery method. You'll need to use .value in JavaScript.
obj[columnHeader[i]] = curr.innerHTML.trim();
innerHtml.trim returns only tag having direct child with text in it. In your code last two td having an input as child.
so in that case you need to check 'curr' having a child available. if there is a child available and its tagName is input, then you have to use childs value.
for example
obj[columnHeader[i]] = curr.children.length && curr.children[0].tagName=="INPUT" ? curr.children[0].value : curr.innerHTML.trim();
the above condition can be check and assign to a variable before it is assigned to key

How can I uncheck the checked row of a table only if the column value matches

Actually I am looking to uncheck the checked row of a table only if the column value of the row matches to my value(value that i am passing). When I check the row from table 1 it binds into table 2.
So with the below script, when I delete a row from the "table 2", I am fetching the column (item code) value of row to be deleted from "table 2" and pass it to another table "table1". Now I want to compare the selected rows column value of "table1". If the column (Item code) value of table 1 matches to "item code" that I am passing, I want to uncheck the row.
But with the below code when I try to delete a row from table 2. it unchecked all the selected rows from table 1. So how can I modify my script to uncheck only only row (matched value row)?
Any help appreciated.
HTML Table
Table 1
<table id="order-table" name="order-table">
<tr>
<th>Select</th>
<th>Medication</th>
<th>Max Issue Limit</th>
<th>Quantity</th>
<th>X</th>
<th>Unit Price</th>
<th>=</th>
<th>Totals</th>
<th>Item Code</th>
</tr>
<tbody id="contacts">
<tr class='odd'>
<td><input type='checkbox' class='single-checkbox' checked></td>
<td class='product-title'>itemName</td>
<td>5</td>
<td class='qty'>2 </td>
<td class='times'>X</td>
<td class='rate'>10.00</td>
<td class='equals'>=</td>
<td class='date-total'>20</td>
<td class='med'>1</td>
</tr>
<tr class='odd'>
<td><input type='checkbox' class='single-checkbox'></td>
<td class='product-title'>itemName</td>
<td>5</td>
<td class='qty'>2 </td>
<td class='times'>X</td>
<td class='rate'>10.00</td>
<td class='equals'>=</td>
<td class='date-total'>20</td>
<td class='med'>2</td>
</tr>
</tbody>
</table>
Table 2
<table id='peopleTable' class='table table-bordered table-condensed table-striped'>
<thead>
<tr><th style='width:475px;'>Item Name</th>
<th>Actual Amount</th>
<th>Bill Amount</th>
<th>Item Code</th>
<th></th>
</tr></thead>
<tbody style='height:135px;overflow:auto'>
<tr>
<td class='name'>Item Name</td>
<td class='price'>25.00</td>
<td>24.00</td>
<td class='midlist'>1</td>
<td>
<button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button>
</td>
</tr>
</tbody>
</table>
Here is my script
function deletePerson(ctl) {
$(ctl).parents("tr").remove();
var sum = 0.00;
$('.price').each(function () {
sum += parseFloat($(this).text());
});
if (sum > 0.00) {
var elem = document.getElementById("grandtotal"); // Get text field
elem.value = sum;
var eleminfo = document.getElementById("ActualAmount"); // Get text field
eleminfo.value = sum;
var elemen = document.getElementById("grandtotalclaim"); // Get text field
elemen.value = sum;
var elemenfees = document.getElementById("ClaimAmount"); // Get text field
elemenfees.value = sum;
}
else {
sum = 0.00
var elem = document.getElementById("grandtotal"); // Get text field
elem.value = sum;
var eleminfo = document.getElementById("ActualAmount"); // Get text field
eleminfo.value = sum;
var elemen = document.getElementById("grandtotalclaim"); // Get text field
elemen.value = sum;
var elemenfees = document.getElementById("ClaimAmount"); // Get text field
elemenfees.value = sum;
}
var value1= $(ctl).parents("tr").find('.midlist').text();
var tableControl = document.getElementById('order-table');
var count = document.querySelectorAll('input[type="checkbox"]:checked', tableControl).length;
$('input:checkbox:checked', tableControl).each(function () {
$(this).closest('tr').find('.med').each(function () {
var te = $(this).text();
if (te == value1) {
alert("matched");
$(this).find('input[type=checkbox]').attr('checked', true);
}
else
{
alert("Not Matched");
}
})
});
}

Is there a better way to setup the input checked attribute?

My first thought was to set the input checked = "javascript function() true/false" is this possible?
What I am trying to do is a select all checkbox for my forum mailbox system.
I am useing a table to display the inbox and placed the select all checkbox inside.
<form action="" method = "post">
<table rules="all">
<tr>
<th>
<input type="checkbox" id = "setchecked" name="smessgage"value="deleteall" onclick="get_checked()"/>
</th>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
I use
onclick="get_checked()
to call this javascript function which sets the other checkboxes checked attribute.
<script>
function get_checked()
{
if(document.getElementById("setchecked").checked)
{
for(var i = 0; i < 100;++i)
{
var check_id = "smessage"+i;
if(document.getElementById(check_id))
document.getElementById(check_id).checked = true;
}
}
else
{
for(var i = 0; i < 100;++i)
{
var check_id = "smessage"+i;
if(document.getElementById(check_id))
document.getElementById(check_id).checked = false;
}
}
}
</script>
The php to set the table up looks like this.
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if(isset($row['to_']) && $row['to_'] == $_SESSION['user_name'])
{
$id_ = isset($row['id']) ? $row['id'] : '';
$top_ = isset($row['subject']) ? $row['subject'] : '';
$auth_ = isset($row['from_']) ? $row['from_'] : '';
$date_ = isset($row['date']) ? $row['date'] : '';
echo '<tr id = "cat_" name = "cat_1">
<td style = "margin:0 auto; text-align:center;"><input type="checkbox" id = "smessage'.$i.'" name="smessgage" value="'.$id_.'"/></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
$auth_.'</a></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
$top_.'</a></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
time_elapsed_string($date_,true).'</a></td></tr>';
++$i;
}
}
This works as expected but seems a bit overkill. I just want to know if there is a more relastic approach or something that I missed while looking over input types?
Here is your improved version. Basically you just need to use same class for all checkbox before each line of your message, so that you can use jQuery.each() function to select all and toggle the checked property based on your main checkbox, which has id "setchecked"
Hope this help,
KD Quality
function checkAll(bx) {
var cbs = jQuery(".checkbox_class").each(function() {
jQuery(this).prop('checked', jQuery('#setchecked').prop('checked'));
});
}
var e = document.getElementById('setchecked'); e.onclick = checkAll;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="post">
<table rules="all">
<tr>
<th>
<input type="checkbox" id="setchecked" name="smessgage" value="deleteall" />
</th>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_1" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_2" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_3" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
</table>
</form>
You could do something like this
// The important code
function selectAll(e) {
var nodes = document.querySelectorAll('form input[type=checkbox]');
for(var i = 0; i < nodes.length; i++) {
nodes[i].checked = e.target.checked;
};
}
// This is only code to genereate input elements
var form = document.getElementById('foo');
for (var i = 0; i < 15; i++) {
var input = document.createElement('input');
input.type = "checkbox";
form.appendChild(input);
}
<input id="selectall" type="checkbox" onclick="selectAll(event)" />
<label for="selectall">Select all</label>
<hr />
<form id="foo"></form>

Categories

Resources