Add two array values of same name using script - javascript

I need to multiply two values of a and b and display in c. Also I need to display the addition value of c using script. Please check my code below:
HTML:
<table border="1" id="table" class="table">
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
<?php
$select= "SELECT * from table where id=1";
$result = mysql_query($select);
$row_count=1;
while($row = mysql_fetch_assoc($result))
{
?>
<tr>
<td><input type="text" value="<?php echo $row['name_a']; ?>" name="name_a[]" class="name_a"></td>
<td><input type="text" value="<?php echo $row['code_a']; ?>" name="code_a[]" class="code_a"></td>
<td><input type="text" name="id_a[]" class="id_a" ></td>
</tr>
<?php
$row_count++;
}
?>
</table>
<input type="text" name="total" class="total">
SCRIPT:
$(document).ready(function() {
$('#table').on('keyup', '.name_a', cal)
.on('keyup', '.code_a', cal)
.on('keyup', '.id_a', cal);
function cal() {
var $row = $(this).closest('tr'),
name_a = $row.find('.name_a').val(),
code_a = $row.find('.code_a').val(),
id_a = $row.find('.id_a').val(),
id_a_calc = name_a * code_a;
$row.find('.id_a').val(id_a_calc)
}
});
OUTPUT
a b c
1 2 2
2 4 8
By the above script,I can multiply a and b and display in c.But how to add two values of 'c' and display in total text box.Need help

try this:
$(document).ready(function() {
$('#table').on('keyup', '.name_a', cal)
.on('keyup', '.code_a', cal)
.on('keyup', '.id_a', cal);
});
function cal() {
var $row = $(this).closest('tr'),
name_a = $row.find('.name_a').val(),
code_a = $row.find('.code_a').val(),
id_a = $row.find('.id_a').val(),
id_a_calc = name_a * code_a;
$row.find('.id_a').val(id_a_calc);
var total = 0;
$(".id_a").each(function() {
// console.log($(this).val());
if($(this).val().length > 0){
total += parseInt($(this).val(), 10);
}
});
$(".total").val(total);
}

Put this in cal after you update $row.find('.id_a').val()
var total = 0;
$(".id_a").each(function() {
total += parseInt($(this).val(), 10);
});
$(".total").text(total);

try this code:-
$(document).ready(function() {
$("#btn").click(function() {
var cValue = 0;
$('#table tr td:nth-child(3)').each(function() {
cValue += parseInt($(this).html());
});
$("#total").val(cValue)
});
});
jsfiddle example:-
http://jsfiddle.net/c2S5d/21/

Related

Onchange in dynamic table only updates input textbox in first row

I want to thank you guys for your response and assistance rendered so far, i am greatful but please i wouldn't mind if you don't get tired on me.
Thanks.
Please i need help with my dynamic table, everything seems to be working fine except for my onchange event for each dynamically added row, it only inserts into the first row, but when i select an option from the second added row, the feilds to be updated from the database remains blank.
I used alert to check, and the onchange seems to be working on all rows just that it is only the first row that changes are effected to the required fields. Bellow is my code for your review.
php script at the top of the page that populates select option data from the database
<?php
$query1 = "SELECT * FROM products";
$result1 = mysqli_query($con, $query1);
$options = "";
while($row3 = mysqli_fetch_array($result1))
{
$options = $options."<option value='$row3[1]'>$row3[2]</option>";
}
?>
My Javascript
<SCRIPT language="javascript">
//function that increases the table row
function addRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[1].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Row Reached.");
}
}
//function that reduces the table row
function deleteRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 2) { // limit the user from removing all the fields
alert("Cannot Remove all the Rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
//function that handles the summing of each row & all last column
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox12 = mainRow.querySelectorAll('[id=item')[0].value;
var myBox23 = mainRow.querySelectorAll('[id=descript')[0].value;
var myBox1 = mainRow.querySelectorAll('[id=uprice')[0].value;
var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
var total = mainRow.querySelectorAll('[id=qty')[0];
var multiplier = Number(myBox2) || 0;
var myResult1 = myBox1 * multiplier;
var mresult = myResult1.toFixed(2);
total.value = mresult;
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
let rows = [...table.querySelectorAll('[name*=qty]')];
let total2 = rows.reduce((prev, current)=>{
let to_be_added = Number(current.value) || 0;
return prev + to_be_added;
},0)
console.log(total2);
$("#sumtotal").val(total2.toFixed(2));
return total2;
}
//function that gets the amount due(balance left)
function amountDue() {
var amount = parseFloat($("#sumtotal").val());
var paidd = parseFloat($("#paid").val());
var balance = amount - paidd;
$("#due").val(balance.toFixed(2));
$("#due2").val(balance.toFixed(2));
//return total2;
}
//function that updates #uprice and #descript from the data base onchange of the select box
function get_item(elementID){
$.ajax({
method:"POST",
url:"get_price.php",
data:{item2:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
//$('#descript').val(data);
$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
$('#descript').val(data);
}else{
alert('Description not available');
}
}
});
}
</SCRIPT>
My html code
<table id="dataTable" class="form">
<thead>
<th style="width:20px"></th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Item Units</th>
<th>Sub Total (#)</th>
</thead>
<tbody>
<tr id='row_0'>
<td><input style="width:20px" type="checkbox" name="chkbox[]" />
</td>
<td>
<select required="required" name="item" onchange="get_item('row_0')" id="item" placeholder="Item">
<option value="0"> select an item</option>
<?php echo $options;?>
</select>
</td>
<td>
<input type="text" required="required" class="small" name="descript" id="descript" placeholder="Description">
</td>
<td>
<input type="text" required="required" name="uprice[]" oninput="calculate('row_0')" id="uprice" placeholder="unit price">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="0">
</td>
<td>
<input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="sub total" value="0.00" readonly="readonly" style="background-color: white">
</td>
</tr>
</tbody>
</table>
<span id="mee"></span>
<input type="button" value="Add" onClick="addRow('dataTable')" class="butto" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" class="butto"/>
Already mentoined here, but still: How to submit form on change of dropdown list? . When user submits form, use php fetch from databse, with isset($_POST['name'])
I was able to fix it with making the some changes in my get_item() javascript function
function get_item(dropDown){
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:dropDown.value},
success:function(data){
alert(data);
if(data!='0'){
$($(dropDown).parents('tr')[0]).find('input#descript').val(data);
//$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
}
thanks everyone.

How to get values from option-list into consecutive input-fields by onclick-function

I have a html-form to read out data from a database.
By clicking a button, there is the possibility to create additional input fields.
<table>
<tr>
<td>
<input type="text" id="productinput" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="productinput2" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="productinput3" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
</table>
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
// Create new div
var newdiv = document.createElement('div');
newdiv.innerHTML = '<br><input type="text" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>';
document.getElementById(divName).appendChild(newdiv);
// Re instantiate Awesomplete
new Awesomplete(newdiv.querySelector('input'), { list: document.querySelector('#productinputselect') });
// Set counter
counter++;
}
}
</script>
<div id="dynamicInput">
<b></b><input type="text" id="productinput4" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>
</div>
<input type="button" value="Additional Input Field" onClick="addInput('dynamicInput');">
<select name="productselect" id="productselect" size="9" onclick="sendproductnameinput()">
<?php
include("../files/zugriff.inc.php"); // database access
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optproduct" value='. $row['Name'] . '>' . $row['Name']. '</option>';
echo '<br>';
}
mysqli_close($db);
?>
</select>
So far, this works fine!
By using the following javascript-function the selected value from the -list is displayed in the first input-field.
function sendproductnameinput() {
document.formdatabase.productinput.value = document.formdatabase. productselect.value;
}
How can I get the next selected value in the second input-field and so on? This function should work in the additionally added fields, too.
You can use this :
for (var i = document.formdatabase.length - 1; i >= 0; i--) {
document.formdatabase[i].value = document.formdatabase.productselect.value;
}
Your Select seems to be not Multiple select, so I suppose you want to put the same selected value in each input.
And if multiple select than you can use this:
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function sendproductnameinput() {
var selected = getSelectValues(document.formdatabase.productselect);
for (var i = document.formdatabase.length - 1; i >= 0; i--) {
if(i < selected.length) {
document.formdatabase[i].value = selected[i];
}
}
}
here is a fiddle https://jsfiddle.net/586menbv/16/
Well, it depends on where the function sendproductnameinput() is defined, but if the variable counter is visible from it's scope, I would dare to write something like this:
var timesSomethingSelected = 1;
function sendproductnameinput() {
var productinput = 'productinput';
if(timesSomethingSelected > 1) {
productinput += timesSomethingSelected;
timesSomethingSelected++;
} else if(timesSomethingSelected == counter) {
//Do something if there aren't more inputs.
}
document.formdatabase[productinput].value = document.formdatabase. productselect.value;
}

Find element based on highest value of inputbox in same table row

I have a table with three columns.
Column 1 has inputboxes.
Column 2 contains a "conversion" number which multiplies it's value with the value in the inputbox (column 1)
and the result is outputted in column 3.
It would look something like this:
5 2 10
1 1 1
2 1 2
3 2 6
How can I get column 3's value based on the highest inputbox value in the same row?
My code so far:
HTML
<table border="1px">
<tbody id="mbtbody">
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">5</td>
<td class="totals"></td>
</tr>
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">1</td>
<td class="totals"></td></tr>
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">1</td>
<td class="totals"></td>
</tr>
</tbody>
</table>
jQuery
$("#btn").click(function(){
var rows = $("#mbtbody").children("tr");
var total = 0;
rows.each(function(idx, row) {
var $row = $(row);
total += parseInt($row.find('input.weightinputclass').val());
$("#totalweight").html(total);
});
})
$(document).on('input', '.weightinputclass', function () {
var $row = $(this).closest("tr");
var weight = $row.find("input.weightinputclass").val();
var conversion= $row.find(".conversionclass").html();
$row.find(".totals").text(weight*conversion);
})
Fiddle: https://jsfiddle.net/rdawkins/9fyLqfgr/16/
Here is a solution I found:
Javascript
$("#btn").click(function(){
var rows = $("#mbtbody").children("tr");
var total = 0;
rows.each(function(idx, row) {
var $row = $(row);
total += parseInt($row.find('input.weightinputclass').val());
$("#totalweight").html(total);
});
var currentMax = 0;
var currentMaxEl;
$('.weightinputclass').each(function (idx, element) {
var elVal = parseInt($(element).val());
if(elVal > currentMax) {
currentMax = elVal;
currentMaxEl = $(element);
}
});
var maxWeight = currentMaxEl.parent().parent().children('.totals').first().html();
$('#highestinput').html(2000 - maxWeight);
})
$(document).on('input', '.weightinputclass', function () {
var $row = $(this).closest("tr");
var weight = $row.find("input.weightinputclass").val();
var conversion= $row.find(".conversionclass").html();
$row.find(".totals").text(weight*conversion);
});
Fiddle
https://jsfiddle.net/9v6j8qub/2/

Putting multiple javascript values into table

I got a script that puts an array of links into 1 frame, and checks their loadtime:
<script type="text/javascript">
$(document).ready(function(){
var array = ['http://www.example1.come', 'http://www.example2.com', 'http://www.example3.com'];
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
$('#1').on('load', function() {
loadTimes.push((new Date()).getTime());
$('#1').attr('src', array.pop());
if (array.length === 0) {
$.each(loadTimes, function(index, value) {
alert(value - beforeLoad);
});
}
}).attr('src', array.pop());
});
</script>
I would like to put all values into a table instead of alerting them. I mean put them in here (creates 3x td's and puts loadingtime values in each):
<table>
<tr>
<?php for ($i=0; $i<=2; $i++){ ?>
<td id="loadingtime<?php echo $i; ?>">
<?php } ?>
</td>
</tr>
</table>
Your PHP loop is a little broken. But that's ok because it is unnecessary - just draw out the 3 TDs.
<table>
<tr>
<td id="loadingtime1">
</td>
<td id="loadingtime2">
</td>
<td id="loadingtime3">
</td>
</tr>
</table>
The short way to add javascript variables to a table is NOT through PHP. You can add them directly using $.().html.
Instead of alert(value - beforeLoad);
Use: $("#loadingtime"+index).html(value - beforeLoad);
You can do that in jquery not php.
$(document).ready(function(){
var array = ['http://www.example1.come', 'http://www.example2.com',
'http://www.example3.com'];
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
$('#1').on('load', function() {
loadTimes.push((new Date()).getTime());
$('#1').attr('src', array.pop());
if (array.length === 0) {
var table = $('<table><tr></tr></table>');
var tr = table.find('tr');
$.each(loadTimes, function(index, value) {
tr.append('<td>' + (value - beforeLoad) + '</td>');
});
table.appendTo('body');
}
}).attr('src', array.pop());
});

How to iterate a table rows with JQuery and access some cell values?

<table class="checkout itemsOverview">
<tr class="item">
<td>GR-10 Senderos</td>
<td><span class="value">15.00</span> €</td>
<td><input type="text" value="1" maxlength="2" class="quantity" /></td>
</tr>
<tr class="item">
<td>GR-10 Senderos<br/>GR-66 Camino de la Hermandad<br/>GR 88 Senderos del Jarama<br/>Camino del Cid</td>
<td><span class="value">45.00</span> €</td>
<td><input type="text" class="quantity" value="1" maxlength="2"/></td>
</tr>
</table>
I was trying with the next code to get the value and quantity of each item.
$("tr.item").each(function(i, tr) {
var value = $(tr + " span.value").html();
var quantity = $(tr + " input.quantity").val();
});
It is not working. Can anyone help me?
$("tr.item").each(function() {
$this = $(this);
var value = $this.find("span.value").html();
var quantity = $this.find("input.quantity").val();
});
do this:
$("tr.item").each(function(i, tr) {
var value = $("span.value", tr).text();
var quantity = $("input.quantity", tr).val();
});
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}

Categories

Resources