Adding the values in multiple textboxes to a single textbox in php - javascript

I've a form which contains a div inside which contains a two textboxes one for service type and another for amount and an add more button. When i click on add more button. The div will get duplicated per onclick. Now I want the values in each amount textbox to be summed up and should be shown in another textbox total. I've created a JS function to show the value entered in amount textbox on onkeyup. But I didn't got any answer.
Here is the code what I've tried so far..
HTML
<table>
<tr id="service">
<td>
<span>Service Type:</span>
</td>
<td>
<input type="text" name="servicetype" id="servicetype" />
</td>
<td>
<span>Amount:</span>
</td>
<td>
<input type="text" name="amount" id="amount" onkeyup="onkeyupsum()"/>
</td>
</tr>
<tr>
<td>
<input type="button" id="addmore" onclick="duplicate()" value="Add More"/>
</td>
</tr>
<tr>
<td><h4 style="text-align:left; padding:0,300px,300px,0;">Total Amount</h4></td>
<td><input type="text" name="tamt" id="tamt"></td>
</tr>
</table>
Javascript:
<script>
var i = 0;
function duplicate()
{ // function to clone a div
var original = document.getElementById('service');
var rows = original.parentNode.rows;
var i = rows.length - 1;
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
}
function onkeyupsum()
{ // calculate sum and show in textbox
var sum = 0;
var amount1= document.getElementById('amount').value;
sum += parseFloat(amount1);
document.submitform.tamt.setAttribute("value",sum );
}
</script>
Can anyone tell me the way to take the textbox values even from duplicated div to textbox.

What you should do is to give inputs common class name and then in onkeyupsum select all inputs and calculate sum in loop:
function onkeyupsum() { // calculate sum and show in textbox
var sum = 0,
amount = document.querySelectorAll('.amount'), i;
for (i = 0; i < amount.length; i++) {
sum += parseFloat(amount[i].value || 0);
}
document.submitform.tamt.value = sum;
}
and input will look like:
<input type="text" name="amount" class="amount" onkeyup="onkeyupsum()" />
Demo: http://jsfiddle.net/mf7wqkq2/

Related

Rewriting JavaScript code with consequent numbers in the names of ids

I'm trying to apply a function to input field with ids that contain consequent numbers (ie. price1, price2, price3), etc.
There's no problem with the first row of field that are defined for a start. But further input fields are dynamically added by a jQuery function and their number is not known in advance.
I hoped it would be an easy loop to apply:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
So far so good - the outcome of the multiplication properly displays in the id="value1" field after the "quantity" field is filled up.
Now further fields should follow the pattern and calculate the value when the quantity is entered - like this:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
etc.
So the code follows:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
The problem is that all further "value" fields are only calculated when "quantity2" is (re)entered and the "value2" is not calculated at all.
I guess there's a mistake while addressing fields and/or triggering the calculation.
How should I correct the code?
Just in case the "add_field" function is needed to solve the problem:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
Incrementing IDs is a lot more trouble than it is worth, especially when you start removing rows as well as adding them.
This can all be done using common classes and traversing within the specific row instance.
To account for future rows use event delegation.
Simplified example:
// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()
// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
const $row = $(this).closest('tr'),
price = $row.find('.price').val(),
qty = $row.find('.qty').val();
$row.find('.total').val(price*qty)
});
$('button').click(function(){
// insert a copy of the stored row
// delegated events will work seamlessly on new rows also
const $newRow = $storedRow.clone();
const prodName = 'Product XYZ';// get real value from user input
$newRow.find('.prod-name').text(prodName)//
$('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>
<table id="myTable">
<tr>
<td class="prod-name">Product 1</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
<tr>
<td class="prod-name">Product 2</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
</table>
Understanding Event Delegation
The first thing to consider is that you can get the length of a selector. So for example:
var count = $("input").length;
If there is one, value here would be 1. if there are four, the value would be 4.
You can also use .each() option to itereate each of the items in the selector.
$('#add_field').click(function(){
var allFields = $('[id^="quantity"]');
allFields.each(function(i, el){
var c = i + 1;
$(el).keyup(function() {
var price = parseFloat($("#price" + c).val());
var quantity = parseInt($(el).val());
var value = price * quantity;
value = value.toFixed(2);
value = value.toString().replace(/\./g, ',');
$("#value" + c).val(value);
});
});
});
You could also create relationship based on the ID itself.
$(function() {
function calcTotal(price, qnty) {
return (parseFloat(price) * parseInt(qnty)).toFixed(2);
}
$('#add_field').click(function() {
var rowClone = $("#row-1").clone(true);
var c = $("tbody tr[id^='row']").length + 1;
rowClone.attr("id", "row-" + c);
$("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
$("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
$("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
$("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
$("button", rowClone).attr("id", "remove-" + c);
rowClone.appendTo("table tbody");
});
$("table tbody").on("keyup", "[id^='quantity']", function(e) {
var $self = $(this);
var id = $self.attr("id").substr(-1);
if ($("#price-" + id).val() != "" && $self.val() != "") {
$("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
<thead>
<tr>
<td>Number</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
<td></td>
</thead>
<tbody>
<tr id="row-1">
<td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
<td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value-1" disabled></td>
<td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
</tr>
</tbody>
</table>

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);

onChange event for calculation in dynamic grid updates wrong rows - Classic asp

I have an old ASP site that needs a change. I need a basic grid to set pricing.
I want to enter a price in one column and have it display text of "Debit" or "Credit" in another column based on positive or negative input. I also want to calculate the extended price based on qty. I've just started with the first (text display) one for now, and can't get it to work.
The grid could have n number of rows based on the data set returned so I have a counter which I concatenate to the input IDs to indicate the row number. The counter is working fine and I can see the id's increment correctly. I've tried to pass the correct input value and id but when the function fires it updates the wrong rows. Actually it updates all the rows below the row I've changed. I have spent WAY too much time banging my head on what I thought would be a 15 min issue. Need a few more pairs of eyes.
<script>
function myFunction(val) {
data_length = document.getElementById("datalength").value;
i = 0;
while(i++ < data_length)
if (val > 0) {
document.getElementById("chargepay" +i).innerHTML = "Credit";
}
else
{
document.getElementById("chargepay" +i).innerHTML = "Debit";
}
}
</script>
Here is the row in the grid loop that has the input field to pass the amount value:
<td align="center"><input id="AMNT<%=count%>" size="10" name="AMNT"
onchange="myFunction(this.value)"/></td>
Here is the row in the grid to display the update from the onchange
<td align="center"><p id="chargepay<%=count%>"</p>td>
When I update the value in the input box in first row, it updates all rows below but not that row. I have a loop, I think. I only want it to update one row at a time as I change the values.
Any help / direction would be appreciated.
If you haven't included you need to include the JQuery library from local system or CDN.
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
You need to add the change even for every input involved in your mathematical calculation. Here 'this; is passed as argument, so that we can find the parent row(through which all other controls contained in it can be searched.
onchange="myFunction(this)"
Inside the function 'myFunction', We at first finds the closest/parent 'tr'.
Again we selects the input field corresponding to Quantity, Amount etc(you can add more if required). The selection can be based on Id, Name, Class etc
var qty = currentRow.find('input[name=QTY]').val();
//or (id starting with 'QTY')
var qty = currentRow.find('input[id*=QTY]').val();
//or (give any class name and replace it instead of 'class-name')
var qty = currentRow.find('input.class-name').val();
We need to convert the string value to float to perform accurate mathematical calculations. While parsing empty string we may end up with 'NAN' - Not a Number. So we need to check before parsing.
qty = (qty == "" ? 0 : parseFloat(qty));
After all this you can use this value for any math calculation and setting it as text of the tag or any other.
If its p, div, span you need to set it as 'text'
currentRow.find('input[name=TOT]').text(totalAmount);
And if its input you need to set it as 'value'
currentRow.find('p[name=TOT]').val(totalAmount);
function myFunction(elem) {
var currentRow = $(elem).closest('tr');
var qty = currentRow.find('input[name=QTY]').val();
var amt = currentRow.find('input[name=AMNT]').val();
qty = (qty == "" ? 0 : parseFloat(qty));
amt = (amt == "" ? 0 : parseFloat(amt));
var totalAmount = qty * amt;
currentRow.find('p[name=TOT]').text(totalAmount);
currentRow.find('p[name=TYPE]').text(totalAmount > 0 ? 'Credit' : 'Debit');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td align="center">
<input id="QTY1" size="10" name="QTY" onchange="myFunction(this)" />
</td>
<td align="center">
<input id="AMNT1" size="10" name="AMNT" onchange="myFunction(this)" />
</td>
<td align="center">
<p id="TOT1" name="TOT"></p>
</td>
<td align="center">
<p id="chargepay1" name="TYPE"></p>
</td>
</tr>
<tr>
<td align="center">
<input id="QTY2" size="10" name="QTY" onchange="myFunction(this)" />
</td>
<td align="center">
<input id="AMNT2" size="10" name="AMNT" onchange="myFunction(this)" />
</td>
<td align="center">
<p id="TOT2" name="TOT"></p>
</td>
<td align="center">
<p id="chargepay2" name="TYPE"></p>
</td>
</tr>
<tr>
<td align="center">
<input id="QTY3" size="10" name="QTY" onchange="myFunction(this)" />
</td>
<td align="center">
<input id="AMNT3" size="10" name="AMNT" onchange="myFunction(this)" />
</td>
<td align="center">
<p id="TOT3" name="TOT"></p>
</td>
<td align="center">
<p id="chargepay3" name="TYPE"></p>
</td>
</tr>
</table>

After swap rows form doesnt send data, javascript

I have a problem, I coded table with some rows, and after that I need to swap some rows after click:
function move_up(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.previousSibling.previousSibling;
var temp = cur.innerHTML;
cur.innerHTML = cur_upd.innerHTML;
cur_upd.innerHTML = temp;
}
function move_down(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.nextSibling.nextSibling;
var temp = cur.innerHTML;
cur.innerHTML = cur_upd.innerHTML;
cur_upd.innerHTML = temp ;
}
I have table with rows like this:
<tr>
<TD >
Typ projektu 1
</TD>
<TD align="center">
<input type="text" class="order_num" name="x_order_num_PROJECT_TYPE" value="1">
<input type="checkbox" name="x_PROJECT_TYPE_on" checked>
</TD>
<td>
Hore
Dole
</td>
<TD align="LEFT">
<select class="selectbox" name="x_PROJECT_TYPE" style="width: 250px">
<OPTION VALUE="-1" SELECTED>Všetky</option>
<OPTION VALUE="1" SELECTED>Fixed price</option>
<OPTION VALUE="2">Time and materials</option>
</select>
</TD>
<TD>▲
<INPUT TYPE="radio" NAME="x_sort" VALUE="PROJECT_TYPE;asc">
<INPUT TYPE="radio" NAME="x_sort" VALUE="PROJECT_TYPE;desc">
▼
</TD>
</TR>
After I click on href 'Hore' or 'Dole' it look good, but problem is, that after swap column when I call form submit, it submit all imputs from all rows except swapped rows. Input from that rows is not submitted. What can be problem?
Don't use innerHTML to move the elements, just move the DOM elements themselves.
function move_up(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.previousSibling.previousSibling;
var parent = cur.parentNode;
parent.insertBefore(cur, cur_upd);
}
function move_down(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.nextSibling.nextSibling;
var parent = cur.parentNode;
parent.insertBefore(cur_upd, cur);
}
If there are any event listeners bound to elements, or the application has variables referencing them, converting them back and forth to HTML will lose that.

How to get values of dynamically created input fields (Json)

input fields are created via jquery depend on user input
If user type Quantity : 5 then i m created 5 input fields
for example if user give Quantity = 3 then this is how the html created dynamically using Jquery
<tr id = "tr_1">
<td><input type="text" name="cont_no1" id="cont_no1" /><td>
<td><input type="text" name="cont_size1" id="cont_size1" /><td>
<td><input type="text" name="cont_type1" id="cont_type1" /><td>
</tr>
<tr id = "tr_2">
<td><input type="text" name="cont_no2" id="cont_no1" /><td>
<td><input type="text" name="cont_size2" id="cont_size2" /><td>
<td><input type="text" name="cont_type2" id="cont_type2" /><td>
</tr>
<tr id = "tr_3">
<td><input type="text" name="cont_no3" id="cont_no3" /><td>
<td><input type="text" name="cont_size3" id="cont_size3" /><td>
<td><input type="text" name="cont_type3" id="cont_type3" /><td>
</tr>
now i need to store all this input fields values in json.
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
i tried like this but its not working the please someone help me. ThankYou
for your refrence here is full code, var auto_tr value is aligned here(with enter) for your purpose .
$(document).ready(function(){
$( "#cont_qty" ).change(function()
{
var itemCount = 0;
$("#munna").empty();
var cont_qty = this.value;
for(var i=0 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'">
<td>
<input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value="">
</td>
<td>
<select class="input-mini" name="cont_size'+itemCount+'" id="cont_size'+itemCount+'">
<option>20</option>
<option>40</option>
<option>45</option>
</select>
</td>
<td>
<select class="input-mini" name="cont_type'+itemCount+'" id="cont_type'+itemCount+'">
<option>DV</option>
<option>HD</option>
<option>HC</option>
<option>OT</option>
<option>FR</option>
<option>HT</option>
<option>RF</option>
</select>
</td>
<td>
<select class="input-medium" name="cont_tonnage'+itemCount+'" id="cont_tonnage'+itemCount+'">
<option>24000 Kgs</option>
<option>27000 Kgs</option>
<option>30480 Kgs</option>
<option>Super Heavy Duty</option>
</select>
</td>
<td>
<input class="input-medium" type="text" id="cont_tare'+itemCount+'" name="cont_tare'+itemCount+'" value="">
</td>
<td>
<input class="input-medium" name="cont_netweight'+itemCount+'" id="cont_netweight'+itemCount+'" type="text" value="">
</td>
<td>
<input class="input-mini" name="yom'+itemCount+'" id="yom'+itemCount+'" type="text" value=""></td>
<td>
<select class="input-medium" name="cont_condition'+itemCount+'" id="cont_condition'+itemCount+'">
<option>IICL</option>
<option>ASIS</option>
<option>CARGO WORTHY</option>
</select>
</td>
</tr>';
$("#munna").append(auto_tr);
}
});
$("#getButtonValue").click(function ()
{
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty.value; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
alert(jsonObj[0].cont_no[1]);
});
});
did small loop mistake :)
for(var i=1; i<=cont_qty.value; i++)
{
alert(cont_qty.value);
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
in previous one i<cont_qty.value this one used now just changed as i<=cont_qty.value
so the loop ran 3 times when qty is 4. now just added <=
ThankYou for your answers friends
Make sure you call your function after you created the html via jquery.
createHtml(); // function to create the html
storeValuesToArray(); // Your function to store data to array
Also make sure you properly close your tags <tr></tr>. And put <tr> inside a <table> tag.
And make sure your cont_qty is set to a value
After you created the html and added all the fields necessary, you can catch all elements by using a selector like:
var jsonObj= jsonObj || [];
$('[name^="cont_no"]').each(function(){
var i = this.name.split('cont_no')[1];
var item = {};
item['cont_no'] = $(this).val();
item['cont_size'] = $('[name="cont_size'+i+'"]').val();
item['cont_type'] = $('[name="cont_type'+i+'"]').val();
jsonObj.push(item);
});

Categories

Resources