With help I've gotten this script to change the class of the function to include countable but need to get the total calculation to update the sum of all fields shown when that change takes place.
The scripts are split with the top one set to calculate the total of all countable class fields and the second script section set to show the line items and add the countable class.
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.countable').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
<script>
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
These checkboxes allow display of the line items when selected.
<input class="my-activity" type="checkbox" value="42"/> example<br/>
<input class="my-activity" type="checkbox" value="43"/> example<br/>
<table id="sum_table">
<tr class="42" style="display:none">
<td>example</td>
<td></td>
<td></td>
<td class="price">7800</td>
</tr>
<tr class="43" style="display:none">
<td>First Area</td>
<td></td>
<td></td>
<td class="price">6900</td>
</tr>
<tr class="totalColumn">
<td>Total:</td>
<td></td>
<td class="totalCol"></td>
</tr>
</table>
You need to load jQuery before you can use it, so move:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
above the other 2 scripts. Then, replace your first script with this:
function showTotal(){
//grab the .countable elements from the #sum_table
var $countables =$("#sum_table .countable");
//loop through and add up the total from their texts
var total = 0;
for(var i = 0; i < $countables.length; i++){
total += Number($countables.eq(i).text());
}
//put the total in the .totalCol element
$("#sum_table td.totalCol").html(total);
}
and call this function at the end of your onchange function, like this:
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
//CALL IT HERE:
showTotal();
});
});
Related
**Currently I have written code for calculating sum of input on my input
for One Table**
$('#example122').on('input', '.calculate', function () {
calculateTotal();
});
function calculateTotal()
{
var grandTotal = 0;
$('#example122 tbody tr').each(function() {
var c_sbt = $('.calculate', this).val();
grandTotal += parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal);
$('.sub_total').val(subT.toFixed(2));
}
**But now i want code for multiple table having same ID **
$('table').foreach(on('input', '.calculate', function () {
calculateTotal();
}));
function calculateTotal()
{
var grandTotal = 0;
$('table tbody tr').each(function() {
var c_sbt = $('.calculate', this).val();
grandTotal += parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal);
$('.sub_total').val(subT.toFixed(2));
}
** this code is not working **
HTML CODE
my table data is a input type="text" i want to calculate when user changes the value
<td style="padding-top:15px;" align="right"><b>TOTAL SALARY</b>
</td>
<td>
<input type="text" style="text-align:right;" name="sub_total" id="sub_total" class="form-control sub_total" autocomplete="off" class="form-group" ></td>
</tfoot>
It's hard to know when you don't have the HTML in your post but I think that your main issue is that you're using the keyword foreach when you try to iterate over your tables. As you can se when you iterate over your rows you use each.
Below is a snippet that does something in line with what it looks like you're after. That is, it iterates over multiple tables and adds the values for each column on each row in each table up.
This is probably not exactly what you're trying to do but might point you in the right direction.
$(document).ready(function() {
$('table').each(function() {
calculateTotal(this);
});
})
function calculateTotal(table) {
var grandTotal = parseFloat($('.sub_total').text());
$(table).find('tbody tr').each(function() {
var c_sbt = $(this).text();
grandTotal += parseFloat(c_sbt);
});
var subT = parseFloat(grandTotal);
$('.sub_total').html(subT.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="this">10.2</td>
</tr>
<tr>
<td class="this">12.3</td>
</tr>
</table>
<table>
<tr>
<td class="this">10.2</td>
</tr>
<tr>
<td class="this">10.22</td>
</tr>
</table>
<p class="sub_total">0</p>
I don't understand why the check() function doesn't want to fire, I know that if I set this function to setInterval(check, 1000) or to function $("#btn-click") it will work but why it doesn't work now? I would appreciate if you explain me
$(function() {
$("#field").on("keyup", function() {
var x = $(this).val();
$("#outcome").text(x);
});
$("#btn-save").click(function() {
var name = $("#outcome").text();
var x = $("table tbody").append("<tr><td>" + name + "</td></tr>")
$("#field").val("");
$("#outcome").text("");
});
check();
function check() {
if ($("table tbody").has("tr")) {
$("table tbody tr td").on("click", function(e) {
var tar = $(e.target);
var b = $(this);
if (tar.is(b)) {
b.css("color", "red");
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type='text' id='field'>
<p>The result is: <span id="outcome"></span></p>
<span id="btn-save" class="btn-save">save</span>
<table>
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
The function fires, but there's no td element to attach events to.
If you want to bind events to elements that will be dynamically generated, you do not need a check function, just use $(body').on(evtType,selector,handler)
Check below for an example. every td you'll add dynamically will still be bound to the event listener, because it's attached to 'body'.
$(function() {
$("#field").on("keyup", function() {
var x = $(this).val();
$("#outcome").text(x);
});
$("#btn-save").click(function() {
var name = $("#outcome").text();
var x = $("table tbody").append("<tr><td>" + name + "</td></tr>")
$("#field").val("");
$("#outcome").text("");
});
check();
function check() {
console.log('firing')
}
$('body').on('click', 'table tbody tr td', function(e) {
var tar = $(e.target);
var b = $(this);
if (tar.is(b)) {
b.css("color", "red");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type='text' id='field'>
<p>The result is: <span id="outcome"></span>
</p>
<span id="btn-save" class="btn-save">save</span>
<table>
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
check() is firing. It's just not doing anything because of your if logic, which had bad selectors pointing to elements (tbody, td) that you don't have.
You won't get a td element in your table until AFTER you click btn-save because that click event handler creates the td elements. Your code wants to run check before that button gets clicked.
I've removed the reference to tbody and changed your td reference to th and now it works:
$(function() {
$("#field").on("keyup", function() {
var x = $(this).val();
$("#outcome").text(x);
});
$("#btn-save").click(function() {
var name = $("#outcome").text();
var x = $("table tbody").append("<tr><td>" +name+"</td></tr>")
$("#field").val("");
$("#outcome").text("");
});
check();
function check() {
console.log("HELLO FROM CHECK!");
if ($("table").has("tr")) {
$("table tr th").on("click", function(e) {
var tar = $(e.target);
var b = $(this);
if (tar.is(b)) {
b.css("color", "red");
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='field'>
<p>The result is: <span id="outcome"></span></p>
<span id="btn-save" class="btn-save">save</span>
<table>
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I am trying to create a row of text boxes dynamically through Javascript and read the values of the textbox in JSON. Later,I have to read JSON and display the values in textarea and this should achieved only though jquery and javascript.
I am able to create the text boxes dynamically but I am unable to read the values in JSON. When I use the jQuery part(mentioned below),the javascript to dynamically create textboxes is not working.Any suggestions please.
<table id="myTable">
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation and Employer</th>
<th>Add</th>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtAge" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="text" id="txtOccupation" /></td>
<td><input type="button" id="btnAdd" class="button-add" onClick="insertRow()" value="add"></input></td>
<td><input type="button" id="btnSave" class="button-add" value="Save"></input> </td>
</tr>
</table>
<script>
var index = 1;
function insertRow()
{
var table=document.getElementById("myTable");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
cell1.appendChild(t1);
var cell2=row.insertCell(1);
var t2=document.createElement("input");
t2.id = "txtAge"+index;
cell2.appendChild(t2);
var cell3=row.insertCell(2);
var t3=document.createElement("input");
t3.id = "txtGender"+index;
cell3.appendChild(t3);
var cell4=row.insertCell(3);
var t4=document.createElement("input");
t4.id = "txtOccupation"+index;
cell4.appendChild(t4);
index++;
}
$(document).ready(function(){
$("#btnsave").click(function ()
{
alert("Hi");
var dataToSend={
'Name':[],
'Age':[]};
dataToSend.Name.push({$("txtName").val().trim()});
dataToSend.Age.push({$("txtAge").val().trim()});
localStorage.setItem('DataToSend', JSON.stringify(DataToSend));
var restoredSession = JSON.parse(localStorage.getItem('dataToSend'));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
alert(restoredSession);
});
});
JSFIddle:http://jsfiddle.net/S7c88/
Since you are using jQuery you can greatly simplify the whole process by using methods like clone().
Here's a working example where I created one array of row objects. Since you aren't doing this in a form, I removed the ID's and just used data-name.
var $row;
function insertRow() {
$('#myTable').append($row.clone());
}
$(function () {
$row = $('tr').eq(1).clone(); /* clone first row for re-use*/
$('#myTable').on('click', '.btnSave', function () {
var dataToSend = [];
$('tr:gt(0)').each(function () {
var data = {};
$(this).find('input').each(function () {
data[$(this).data('name')] = this.value
});
dataToSend.push(data);
});
/* display data in textarea*/
$('#output').val(JSON.stringify(dataToSend, null, '\t'))
});
}) ;
I changed your input type=button to button to take advantage of using input selector while looping rows to create data and not have to filter out the buttons
Your demo has invalid html, missing <tr> for top set of <th>
DEMO
Some areas where you were going wrong:
$("txtName") Invalid selector
No row references in attempt to gather data
Please can someone tell me why the first row gets and index value of 1 but every other new row also get 1 instead of 2,3,4 and so on.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<form>
<table>
<thead>
<tr>
<th scope="col">Track</th>
<th scope="col">Album</th>
<th scope="col">Artist</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="track[0]" id="track"></td>
<td><input name="album[0]" id="album"></td>
<td>
<select name="artist[0]" id="artist">
<option value="">Please select</option>
<option value="1">Joe Bloggs</option>
<option value="2">Jack Bloggs</option>
<option value="3">Tina Bloggs</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<button>Add Row</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function($)
{
// trigger event when button is clicked
$("button").click(function()
{
// add new row to table using addTableRow function
addTableRow($("table"));
// prevent button redirecting to new page
return false;
});
function addTableRow(table)
{
var $tr = $(table).find("tr:last").clone();
alert($tr);
var fname = $("#track").attr("name");
var nid = fname.match(/\[(.*?)\]/g);
var idx = nid[0];
idx = idx.replace(/[[\]]/g,'')
var n = fname.split("[");
idx = parseInt(idx) + 1;
$tr.find("input,select").attr("name", n[0] + "[" + idx + "]");
$(table).find("tbody tr:last").after($tr);
};
});
</script>
</body>
I cant seem to work out how to add a new row every time increasing the "name" of each table element by 1 every time ready to use an AJAX post.
The new rows are being created wrong. Artist and Album elements name are always track[0]
Wouldn't be easier to do something like this?
function addTableRow(table) {
var index = $(table).find("tbody tr").length;
var $tr = $(table).find("tr:last").clone();
$tr.find("input,select").each(function (i, k) {
var old_name = $(k).attr("name");
var new_name = old_name.replace(index-1, index);
$(k).attr("name", new_name);
});
$(table).find("tbody tr:last").after($tr);
};
DEMO
Also, consider to give a class instead of a id in every input/select and give a id to the row. It would be easier to work with. as #HMR said when cloning the tr the inputs and select id's are cloned as well, adding the row then causes multiple elements with the same id's. This is not good, make sure each element as a unique ID
How about just counting tr in the tbody instead:
function addTableRow(table)
{
var $tr = table.find("tbody").find("tr").last().clone();
var fname = $("#track").attr("name");
var nid = fname.match(/\[(.*?)\]/g);
var new_idx = table.find('tbody').find('tr').length;
var n = fname.split("[");
idx = parseInt(idx) + 1;
$tr.find("input,select").attr("name", n[0] + "[" + new_idx + "]");
$(table).find("tbody tr:last").after($tr);
};
I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery
If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/
You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});