Javascript- Add row dynamically contain dropbox and formula - javascript

I have a table consist of 5 column: Code, Name, Qty, Price, and Total.
Code contain a dropbox menu which dynamically retrieve from another table. If user click the dropbox and select a code, name of the item will appear automatically in Name column.
For Total column, the value will appear from multiplying Qty and Price. The multiply script I used is:
<script language="javascript" type="text/javascript">
function multiply()
{
a=Number(document.calculator.qty.value);
b=Number(document.calculator.price.value);
c=a*b;
document.calculator.total.value=c;
}
</script>
My code for the table as below:
<table id="theTable" border="1">
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<thead>
<tr>
<th> Code </th>
<th> Name </th>
<th> Qty </th>
<th> Price </th>
<th> Total </th>
<tr>
</thead>
<tbody>
<tr id="templateRow">
<td type="text" name="code" id="code"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("inventory");
$result = mysql_query("select * from input_code_data");
$jsArray = "var code = new Array();\n";
echo '<select name="code" onchange="changeValue(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['code'] . '">' . $row['code'] . '</option>';
$jsArray .= "code['" . $row['code'] . "'] = {name:'" . addslashes($row['name']) . "',desc:'".addslashes($row['name'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="name" id="name"/readonly>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('code').value = code[id].name;
document.getElementById('name').value = code[id].desc;
};
</script>
</td>
<td><input type="text" name="qty"></td>
<td><input type="text" name="price"></td>
<td><input type="text" name="total" /readonly><INPUT type="button" value="Click" onclick="javascript:multiply();"></td>
</tr>
</tbody>
</table>
<INPUT type='button' value='+' onclick="addRow('theTable')" />
If I click add row, then a new row will appear and the format is right. The problem is, when I select a code (from the dropbox) in second row, the name appear in the first row instead, not in the second row. Another problem, Click button for multiply isn't working in the second row.
Would anybody tell me how I fix this? Thanks.

It's because your changeValue(id) function is being called with the select field's value, not the row Id. Additionally, you're getting element by static id's instead of passing them in. HTML assumes that an Id will only appear once per page, you're breaking that so it always returns the first match.
EDIT for some example code:
This deals with some of the issues (if I'm understanding you properly). You might find the MDN docs helpful around how ids and other selectors work.
multiply suffers from the same issues as your original code, but you should be able to figure it out based on what is below:
<table id="theTable" border="1">
<thead>
<tr>
<th> Code </th>
<th> Name </th>
<th> Qty </th>
<th> Price </th>
<th> Total </th>
<tr>
</thead>
<tbody>
<tr class="templateRow" id="invoice-line-1">
<td class="code">
<select onchange="changeValue(this.value, 'invoice-line-1')">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<!-- etc. -->
</select>
<span></span>
</td>
<td class="name"></td>
<td><input type="text" name="qty"></td>
<td><input type="text" name="price"></td>
<td>
<input type="text" name="total" /readonly>
<input type="button" value="Click" onclick="javascript:multiply();">
</td>
</tr>
</tbody>
</table>
<input type='button' value='+' onclick="addRow('theTable')" />
<script type="text/javascript">
var codes = {
"1": {value: 1, name: "Option 1"},
"2": {value: 2, name: "Option 2"},
// etc.
},
numRows = 1;
function changeValue(value, id){
document.querySelector('#' + id + ' td.name').innerHTML = codes[value].name;
document.querySelector('#' + id + ' td.code > span').innerHTML = code[value].value;
};
function addRow() {
var newRow = document.getElementById("invoice-line-1").cloneNode(true),
table = document.querySelector("#theTable > tbody");
newRow.id = "invoice-line-" + (numRows = numRows + 1);
table.appendChild(rewRow);
document.querySelector("#invoice-line-" + numRows + " .code > select").setAttribute('onchange', "changeValue(this.value, 'invoice-line-" + numRows + "')");
}
</script>

Related

How to get the value of input type text from the last row of a table

I have a table in my page and i have input type text in each row, one of them is for srno
I want to get the value of srno text box from the last row of the table using JavaScript.
Here's a code snippet with my HTML:
<table id="vattable" class="table table-sm table-striped">
<thead class="thead-light">
<tr>
<th style="width:50px">SRNo</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="text-control input-sm" readonly name="srno[]" id="srno" value=1 style="text-align:right;max-width:40px;" maxlength="13" /></td>
</tr>
</tbody>
</table>
Actually I am adding rows on button click event in JavaScript, I want to get the last value of srno column and give the next srno with +1 each time the row is created in the table. when the page is loaded I am selecting data from database and fetching in this table so sometime this table may have few rows already and when I click button to create row it should take the last srno and add +1 to the new row srno.
I think that this should work for you if you have a similar HTML structure.
What it basically does is:
Scanning the table structure for all inputs with name=srno.
Getting the last input and logging in the javascript console.
You can get its value with lastInput.value.
function getLastInput() {
//get all inputs with name srno in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
return lastInput;
}
$(document).ready(function() {
var rowcnt = $('#vattable tr').length;
var count = rowcnt;
$(document).on('click', '#addrow', function() {
count = count + 1;
var html_code = '';
html_code += '<tr id="row_id_' + count + '">';
html_code += '<td><input type="text" class="text-control input-sm" name="srno[]" id="srno" readonly style="text-align:right;width:40px" value="' + count + '"/></td>';
html_code += '</tr>';
$('#vattable').append(html_code);
console.log(getLastInput());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="vattable">
<tr>
<td>
<input type="text" name="srno[]" value="1" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="2" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="3" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="4" />
</td>
</tr>
</table>
<button id="addrow">Add row</button>
EDIT:
Use this if your input name is srno[].
//get all inputs with name srno[] in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
console.log(lastInput);

Adding more values from another field with JavaScript

Need help to solve a JavaScript problem.
i am working on an invoice in which i want to add more values to quantity field.
i am trying with script given in JSFiddle.
The problem is when i click on edit , it should popup a dialog box and by entering data in add field it should be added to current quantity of a specific item.
https://jsfiddle.net/programmer/LLmrp94y/16/
JS script
$(document).on('change', '.addQty', function () {
id_arr = $(this).attr('id');
id = id_arr.split("_");
add = $('#add_'+id[1]).val();
qty = $('#quantity_'+id[1]).val();
if (add != '' && typeof (add) != "undefined") {
$('#add_'+id[1]).val();
added = parseFloat(qty) + parseFloat(add);
$('#qtY_'+id[1]).val(added);
priceAfter = $('#price_'+id[1]).val();
$('#Total_'+id[1]).val((parseFloat(priceAfter) * parseFloat(added)).toFixed(2));
} else {
$('#quantity_'+id[1]).val(qty);
$('#Total_'+id[1]).val((parseFloat(price) * parseFloat(qty)).toFixed(2));
}
});
I made it work by doing the following :
adding an id to your edit buttons, so we can retrieve the id of the line currently being edited
replacing your 'onchange' function by a addQuantity function that takes a parameter : the id of the line being edited.
fixing a couple issues with the ids used in the code written to calculate the new quantity and the new price
Also, I replaced your php code by hard coded ids. You're going to have to replace them.
EDIT : Since you don't want to show the current quantity in the dialog, I had to change the logic and update the table after close has been clicked. Otherwise it caused too many issues. Hope you like it.
$(document).ready(function() {
calculateEachItemSubCost();
});
function calculateEachItemSubCost() {
var qtys = document.getElementsByClassName('quantity');
var price = document.getElementsByClassName('price');
var item_costs = document.getElementsByClassName('totalLinePrice');
for (var i = 0; i < item_costs.length; ++i) {
item_costs[i].value = parseFloat(qtys[i].value) * parseFloat(price[i].value).toFixed(2);
}
}
/* new function that replaces your 'onchange' listener. It handles the adding of a quantity on a given line, identified by the id parameter */
function addQuantity(id) {
var add, added, priceAfter;
add = $('#addedQuantity').val();
console.log("Adding " + add + " on line " + id);
if (add != '' && typeof add != "undefined") {
;
added = parseInt($('.add').val()) + parseInt($('#quantity_' + id).val())
$('#quantity_' + id).val(added);
priceAfter = $('#price_' + id).val();
$('#total_' + id).val((parseFloat(priceAfter) * parseFloat(added)).toFixed(2));
} else {
$('#quantity_' + id).val(qty);
$('#Total_' + id).val((parseFloat(price) * parseFloat(qty)).toFixed(2));
}
}
$(document).on('click', '.editnow', function(event) {
var lineId, quantityField;
// retrieving the id of the line that was clicked on
lineId = event.target.id.split("_")[1];
quantityField = $("#quantity_" + lineId);
$(".add").val("");
$("#edit").dialog({
show: "fold",
hide: "fold",
modal: true,
title: "Edit",
zIndex: 10000,
close: function(event, ui) {
addQuantity(lineId);
$(this).hide();
}
});
});
#edit{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css"/>
<!DOCTYPE html>
<!-- Begin page content -->
<h1 class="text-center title">Invoice</h1>
<table>
<thead>
<tr>
<th width="38%">Item Name</th>
<th width="15%">Price</th>
<th width="15%">Quantity</th>
<th width="15%">Total</th>
<th width="15%">Edit</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="samsung galaxy s6" id="itemName_1" ></td>
<td><input type="number" value="500" id="price_1" class="price"></td>
<td><input type="number" value="1" id="quantity_1" class="quantity"></td>
<td><input type="number" value="" id="total_1" class="totalLinePrice"></td>
<td><button type="button" class="editnow" id="edit_1"> Edit </button></td>
</tr>
<tr>
<td><input type="text" value="samsung galaxy s7" id="itemName_2" ></td>
<td><input type="number" value="700" id="price_2" class="price"></td>
<td><input type="number" value="1" id="quantity_2" class="quantity"></td>
<td><input type="number" value="" id="total_2" class="totalLinePrice"></td>
<td><button type="button" class="editnow" id="edit_2"> Edit </button></td>
</tr>
</tbody>
</table>
<div id="edit">
<table>
<tr>
<th>Add</th>
</tr>
<tr>
<td><input type="number" class="add" id="addedQuantity"></td>
</tr>
</table>
</div>
Your updated JSFiddle
I have edited it, but it does not work because of the php values not working, of course. I've added id to Edit buttons, and getting value from dialog. Based on the button id, you can enter value to corresponding quantity field
<button type="button" id="edit_<?php $i; ?>" class="editnow"> Edit </button>
Yes: function () {
var id = $(this).attr('id');
id = id.substring(id.indexOf('_')+1);
alert($('#quantityVal').val()); // just check the value
$('#quantity_'+id).val($('#quantityVal').val());
$(this).dialog("close");
},
Edit dialog number field
<td><input type="number" class="add" id="quantityVal"></td>
https://jsfiddle.net/LLmrp94y/12/

Total of a particular column from html table having multiple rows

My Java Script Code
<script>
$(function(){
$('#addRow').click(function(){
var html = $('#row_template').html();
$('#dataTable').append(html);
$(".tablerow").each(function(index) {
$(this).html(index + 1);
});
});
$('#deleteRow').click(function(){
$('#dataTable .mychkbox:checked').parents('tr').remove();
});
$('#dataTable').on('change','.select-desc',function(){
var cur_val = $(this).val();
$(this).parents('tr').find('input[name="rate[]"]').val(cur_val);
});
$('#dataTable').on('keyup','input[name="qty[]"]', function(){
var qty = +$(this).val();
var unit = +$(this).parents('tr').find('input[name="rate[]"]').val();
$(this).parents('tr').find('input[name="amt[]"]').val(qty*unit);
var totamt = 0 ;
var theTbl = document.getElementById('dataTable');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
totamt = totamt + theTbl.rows[i].cells[4].InnerHTML;
}
}
});
});
</script>
My HTML Code is
<!DOCTYPE html>
<html>
<div class="left">
<h2><span class="orange">Work Order Items</span></h2>
<table>
<tr>
<td><input type="button" value="Add Row" id="addRow" /></td>
<td><input type="button" value="Remove Row" id="deleteRow" /></td>
</tr>
</table>
</div>
<table id="dataTable" class="form" border="0" width='100%'>
<tr>
<td></td>
<td>No</td>
<td>Item Description</label></td>
<td>Qty</td>
<td>Rate</td>
<td>Amount</td>
<td>Cert No</td>
<td>C Date</td>
</tr>
</table>
<table id="row_template" style="display:none">
<tr>
<td><input type="checkbox" name="chk[]" class="mychkbox" /></td>
<td class="tablerow"></td>
<td>
<?php
$sql = "SELECT itrate,CONCAT(itname,'|',itcode) as mname FROM ITMAST ";
$result = mysql_query($sql) or die(mysql_error());
echo "<select name='itname[]' id='itname' class='select-desc' >";
echo "<option value=''>-- Select Item --</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value = '{$row['itrate']}'";
if ($pitcode == $row['itrate'])
echo "selected = 'selected'";
echo ">{$row['mname']}</option>";
}
echo "</select>";
?>
</td>
<td><input type="text" name="qty[]" id="qty" size="6" class='rightJustified'></td>
<td><input type="text" name="rate[]" id="rate" size="8" class='rightJustified' readonly></td>
<td><input type="text" name="amt[]" id="amt" size="9" class='rightJustified' readonly></td>
<td><input type="text" maxlength="10" size="8" name="txtcertno[]"></td>
<td><input type="date" maxlength="10" size="10" name="txtcdate[]"></td>
</tr>
</table>
</html>
I am trying to take total of amount column i.e. amt[] after each entry of a row, but I am not getting it properly, I have written Javascript function for the same but some thing may be wrong in it
I did not correct all of your mistakes,
You should check #Samurai answer for more details (such as use of the 'id' and other things)
Main problem was, as I said in comment, use of innerHTML which returned "
another thing, your theTbl var was not good, you could never call .length on it. To solve that, you had to handle it this way :
var totamt = 0 ;
var theTbl = $('#dataTable');
//You are using jquery, so use jquery selectors...
var trs = theTbl.find("input[name='amt[]']");
//find there the AMT[] INPUTS, not the rows...
console.log("how many amt inputs? : "+trs.length);
for(var i=0;i<trs.length;i++)
{
//fetch the inputs, and make your calculations here
console.log("amount from row "+i+" = "+trs[i].value);
//do not forget, as Samurai said, to convert html to numeric...
$("#total").html(totamt+=parseFloat(trs[i].value));
}
Here is a working solution :
http://jsfiddle.net/nxm0ye54/20/
First to point out a few mistakes:
$('#row_template').html(): browsers automatically add tbody to the table, so you end up having multiple tbody in your main table which of course won't cause any problem on its own, if that's the desired output.
You're misusing ID. Each tr has multiple td with inputs that share the same ID. Instead you should use class.
To calculate the total amount you're getting the innerHTML of the cells which don't hold a number, but an input element. Instead you want the value these input elements are holding.
You need to convert the values to numbers before doing math on them, otherwise it will assume they're string and just put them beside each other. (e.g. 0+1+2 = 012 and not 3). You should use parseInt or parseFlout which the latter suits this case better.
A few modifications to your code:
$('#addRow').click(function () {
var html = $('#row_template tbody').html();
$('#dataTable tbody').append(html);
And - since you're using jQuery - I completely changed the calculation to a jQuery version:
//gt(0) cause the first row contains headers
//eq(5) cause we want the 6th cell (Amount)
var totamt = 0;
$('#dataTable tr:gt(0)').each(function() {
var newAmt = $(this).find('td:eq(5) input[type=text]').val();
totamt += parseFloat(newAmt);
});

Take checkbox values and add them to text input

I have a text input that holds email addresses, each one gets separated by a , to indicate a breaking point for php.
<input type="text" name="to" class="form-control">
Rather than having to retype every email address every time, I have came up with a table that holds all my email addresses and allows me to select the ones I want to send emails to.
<table class="table">
<thead>
<tr>
<th>
</th>
<th>
Client
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
<?php foreach($clients as $client): ?>
<tr>
<td>
<input id="toList" name="to" type="checkbox">
</td>
<td>
<?php echo $client->name.' '.$client->last_name; ?>
</td>
<td>
<?php echo $client->email; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Add To Email
Now, I just need to figure out a way, using javascript that when the add button is clicked javascript adds all the values of all the checked checkboxes to the to input field dividing each one by ,.
hi i have created a jsfiddle for you..
code:-
$(document).ready(function() {
$("#btn").click(function() {
var checkedEmails = $("input[name=to]:checked").closest("tr");
var data = [];
$.each(checkedEmails, function() {
data.push($.trim($(this).find("td:eq(2)").text()));
});
var str = data.join(",");
$("#txt").val(str);
});
});
working example:-
http://jsfiddle.net/XUjAH/1102/
thanks
Change your checkbox to look like this
<input id="toList<?php echo $counter; ?>" class="email-check-box" name="to" type="checkbox" value="<?php echo $client->email;?>">
Javascript part
$(".add").on("click", function() {
$('.email-check-box').each(function () {
var current= (this.checked ? $(this).val() : "");
if(current) {
$(".form-control").val(
$(".form-control").val() + current+ ","
);
}
});
});

Change cell value depending on input of another cell with JavaScript

thanks to peoples help on here I have nearly finished what I set out to do yesterday/
I have included a fiddle here http://jsfiddle.net/uzW5e/
I would like it that when someone enters a value greater than 85 in the column headed Percentage Grade (class percGrade) the value 1 is put in the column headed Pass Level (class passLevel) but it isn't working?
<table align="center">
<tr>
<th>
Module
</th>
<th>
Percentage Grade
</th>
<th>
Credits
</th>
<th>
Pass Level
</th>
<th>
WGC
</th>
</tr>
<tr class="multRow">
<td>
<input name="module" />
</td>
<td>
<input name="percentageGrade" class="percGrade" />
</td>
<td>
<input name="credits" class="credits"/>
</td>
<td>
<input name="passLevel" class="passLevel"/>
</td>
<td>
<span class="multTotal">0.00</span>
</td>
</tr>
<tr>
<td colspan="5" align="right">
Total <span id="grandTotal">0</span>
</td>
<script>
$(document).ready(function () {
$(".multRow input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.multRow").each(function () {
// check value entered for Percentage Grade
// & change Pass Level to value accordingly
var $num = 0;
if ($('.percGrade', this).val() > 85) {
$num = 1;
$('.passLevel',this).text($num);
}
// get the values from this row:
var $val1 = $('.credits', this).val();
var $val3 = $('.percGrade', this).val();
var $val2 = $('.passLevel', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
Since .passLevel is a text field, you should use .val instead of .text:
$('.passLevel',this).val($num);

Categories

Resources