HTML array multiply javascript - javascript

HTML code
<input name="itemCode[]" value="" class="tInput" id="itemCode" tabindex="1"/> </td>
<input name="itemDesc[]" value="" class="tInput" id="itemDesc" readonly="readonly" /></td>
<input name="itemQty[]" value="" class="tInput" id="itemQty" tabindex="2" onchange="multiply(this)"/></td>
<input name="itemPrice[]" value="" class="tInput" id="itemPrice" readonly="readonly" /> </td>
Javascript code
function multiply(el) {
var i= el.value * document.getElementById('itemPrice').value;
document.getElementById('itemPrice').value =i;
}
Problem is this:
the first row in the table multiplies correctly but the second row doesn't work....please help

Problem is that you cannot identify the row correctly with itemXxxxx alone.
It's better to use some id to identify the "row" you are referring to.
For example something like (for every row, in this case row/item no. 23):
<input id="price23" .....>
<input id="qty23" ......>
<input id="total23" onchange="calc(23);" ...>
function calc(id) is:
function calc(id)
{
var p = document.getElementById("price"+id).value;
var q = document.getElementById("qty"+id).value;
document.getElementById("total"+id).value = p * q;
}
It is easy to inject row number from some serverside code.
Edit: Another option would be using JQuery with some DOM traversals between parents and siblings to get the desired values.

Related

How to calculate in this JQuery

I have a problem in jQuery in html. Just need some changes in calculation, below are my codes All result will be calculated in one field as I did
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1"></script>
<script>
$(document).on('keyup','input.expenses','input.deductions',function(){
$expenses = $(this).parents('tr').find('.expenses');
$deductions = $(this).parents('tr').find('.deductions');
$expenseTotal = $(this).parents('tr').find('#total');
$expenseTotal.val('0');
$.each($expenses,function(index,object){
if($(object).val()!='')
{
$expenseTotal.val(parseInt($expenseTotal.val())+parseInt($(object).val()));
}
})
});
</script>
</pre>
< <tbody>';
foreach($data as $d)
{
print '<tr>
<td>'.$d["staff_name"].'</td>
<td><input type="hidden" name="txtid[]" value="'.$d["id"].'">
<input type="text" name="txtbasic[]" class="form-control expenses">
</td>
<td><input type="text" name="txtallowance[]" class="form-control expenses"></td>
<td><input type="text" name="txtsocso[]" class="form-control deductions"></td>
<td><input type="text" name="txtkwsp[]" class="form-control deductions"></td>
<td><input type="text" id="total" name="txttotal[]" class="form-control"></td>
</tr>';
}
print '</tbody>
Existing result
txttotal = txtbasic + txtallowance
The result i need is
txttotal = txtbasic + txtallowance - txtsocso - txtkwsp
Then display the result on key up, Please anyone can help me
There are a few logic/structure issues with your code so I'll first explain each of them, then at the bottom you can find the resulting code
KeyUp event wrong syntax
To be sure you listed to the keyup even on all fields, you need to separate with the comma within the same parameter, so instead of being
on('keyup','input.expenses','input.deductions',function()
It must be
on('keyup','input.expenses, input.deductions',function()
Using ID in loop
You're using a foreach loop to generate your table rows. So you'll have a lot of rows with the same content, which is fine. However, for the last cell of your row, you're using id="total" which is wrong because in any HTML page there can only be 1 element with a unique id. With your code, you will have all rows having the same ID for the last td.
So you need to remove the ID and use a class instead.
From
input type="text" id="total" name="txttotal[]" class="form-control"
You go to
input type="text" name="txttotal[]" class="form-control total"
Correctly loop the elements
Currently your code only loops the .expenses so the txtbasic and txtallowance values. You also need to loop the deductions to obtain txtsocso and txtkwsp
Final Code
Javascript
<script>
$(document).on('keyup', 'input.expenses, input.deductions', function () {
var total = 0;
// Adding txtbasic and txtallowance
$expenses = $(this).parents('tr').find('.expenses');
$.each($expenses, function (index, object) {
var val = parseInt($(object).val())
if(!isNaN(val) && val) {
total += parseInt($(object).val());
}
});
// Adding txtsocso and txtkwsp
$deductions = $(this).parents('tr').find('.deductions');
$.each($deductions, function (index, object) {
var val = parseInt($(object).val())
if(!isNaN(val) && val) {
total -= parseInt($(object).val());
}
});
// Updating the Total
$expenseTotal = $(this).parents('tr').find('.total');
$expenseTotal.val(total)
});
</script>
HTML TR Code
<tr>
<td>'.$d["staff_name"].'</td>
<td><input type="hidden" name="txtid[]" value="'.$d["id"].'">
<input type="text" name="txtbasic[]" class="form-control expenses">
</td>
<td><input type="text" name="txtallowance[]" class="form-control expenses"></td>
<td><input type="text" name="txtsocso[]" class="form-control deductions"></td>
<td><input type="text" name="txtkwsp[]" class="form-control deductions"></td>
<td><input type="text" name="txttotal[]" class="form-control total"></td>
</tr>
</tbody>
</table>
``

Java Script Function Not working in second loop

When the page load the loop start and the java script function also work in the first row of loop but in the second loop it not working the multiplication does not work you can see in the pic ( unit rate * quantity = total price)
foreach($db->getRecordSet($sqlTrRecord) as $row){$counter += 1; ?>
<tr id="temTr" class="banktblhd">
<td width="5"> <?php echo($counter); ?> </td>
<td class="w10"> <input type="text" name="item_code" id="item_code" class="form-control" value="<?php echo($row['item_code']); ?>" readonly /></td>
<td class="w20"><input type="text" class="form-control" name="item_name" id="item_name" value="<?php echo($row['item_name']); ?>" readonly /> </td>
<td class="w10"><input type="text" class="form-control" name="description" id="description" value="<?php echo($row['description']); ?>" readonly /></td>
<td class="w10"><input type="text" class="form-control" name="availableQty" id="availableQty" value="<?php echo($row['quantity']); ?>" readonly /></td>
<td class="w10"><input type="text" class="form-control" name="unit_rate" id="unit_rate" onKeyUp="total()" value="<?php echo($row['unit_rate']); ?>" readonly /></td>
<td class="w10">
<input type="number" class="form-control" name="quantity" id="quantity" onKeyUp="total()" autocomplete="off" /> </td>
<td class="w10"><input type="text" class="form-control" name="total_price" id="total_price" value="" />
</td>
</tr>
--------------------------
function total(){
var unitRate= document.getElementById("unit_rate");
var qty = document.getElementById("quantity");
var total = unitRate.value * qty.value;
document.getElementById("total_price").value = total;
}
You cannot give the same ID to more than one element. It's invalid HTML. If you do, getElementById will typically return the first (but it could do anything, including returning none, since again it's invalid).
In your case, the minimal changes necessary to make this work are:
Remove all those ids in the rows, you don't need them. Keep the names on the inputs.
Pass this into total everywhere you call it so it knows what element the keyup occurred on, e.g.:
<input type="number" class="form-control" name="quantity" onKeyUp="total(this)" autocomplete="off" />
<!-- --------------------------------------------------------------------^^^^ -->
Update total to receive that as a parameter, and to find the various inputs in the same row by traversing the DOM:
function total(element) {
var row = element.closest("tr");
var unitRate = row.querySelector("input[name=unit_rate]");
var qty = row.querySelector("input[name=quantity]");
// (Note you're relying on implicit coercion from string to number here)
var total = unitRate.value * qty.value;
row.querySelector("input[name=total_price]").value = total;
}
That works by finding the row containing the element the event occurred on, and then using Element#querySelector with CSS selectors to find the various inputs within that row.
Note that that uses Element#closest, which is fairly new. To avoid using it, you could replace
var row = element.closest("tr");
with
var row = element;
while (row && row.tagName !== "TR") {
row = row.parentNode;
}
A couple of side notes:
keyup isn't a reliable event to use to update the total field, because it doesn't fire if the user updates the field via the mouse (for instance, right-clicking and choosing paste from the context menu). I'd suggest using the input event.
Using onxyz-attribute-style event handlers is not best practice, not least because they can only call global functions (or methods on the element, containing form if any, etc.). Instead, you could use an event handler registered on the table and use the target of the event object to know which element the event targeted (and thus what row to work in). That's possible because input and keyup both bubble.

How can round multiple inputs with the same id?

I did a script using JQUERY 1.6 to round input, so when I type a long number my script will automatically round 2 decimals.
But is only working with the first input and is not working with other inputs with the same input ID
Here is the live demo
<script>
jQuery("#round_inputs").live("change", function(){
input_values = parseFloat(jQuery("#round_inputs").val());
if (isNaN(input_values)) input_values = "";
jQuery("#round_inputs").val(input_values.toFixed(2));
});
</script>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
Please somebody can help me?
As was pointed out in the comments, ID must be unique, so use classes instead. And you need to refer to each input with jQuery(this), otherwise you're just referring to the first element with the class:
jQuery(".round_inputs").live("change", function () {
input_values = parseFloat(jQuery(this).val());
if (isNaN(input_values)) input_values = "";
jQuery(this).val(input_values.toFixed(2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
<br/>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
<br/>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
Also, as of jQuery 1.7 .live() has been deprecated in favor of .on(), so consider updating your code accordingly.
First off. ID's in a HTML page is supposed to be unique.
Use classes instead.
Avoid inline styles , use CSS to keep your HTML clean.
Inside the change handler use $(this) to target the element that triggered the event.
Use on instead of live which is now deprecated.
JS
$(".round_inputs").on("change", function () {
var input_values = parseFloat($(this).val());
if (isNaN(input_values)) input_values = "";
$(this).val(input_values.toFixed(2));
});
HTML
<input class="round_inputs" size="20" type="text" />
<br/>
<input class="round_inputs" size="20" type="text" />
<br/>
<input class="round_inputs" size="20" type="text" />
<br/>
CSS
.round_inputs {
text-align:right
}
Check Fiddle
When using ID Selectors, jQuery will only ever return the first instance. You should use a classname selector for this:
<input id="round_input1" class="round-input" size="20" style="text-align:right" type="text"/><br/>
And change your jQuery selector to: jQuery('.round-input')
https://api.jquery.com/id-selector/

Can not pass html array to JS

Hi I'm having trouble sending html form array to JS. I have dynamic html form and some fields:
<div id="fields">
<input type="text" name="ppav[]" id="p" />
<input type="text" name="quantity[]" id="q" size="3" />
<input type="text" name="price[]" id="pr" size="10" />
<input type="text" name="sum" id="su" size="10" disabled="disabled"/>
<br />
</div>
in JS i tried using this function but getting undefined alert instead of result:
var welements = document.getElementsByName('ppav[]');
for (var i = 0, j = welements.length; i < j; i++) {
var an_element = welements[i];
alert(an_element.selectedIndex);
}
What did you expect? the selectedIndex property returns the index of the selected option in a select element. If you want the value of your input fields, try alert(an_element.value);

Subtotal of Values in HTML Table

I have a table laid out like so:
<table border="0">
<tr>
<td>10: <input type="text" size="1" autocomplete="off" name="10"/> </td>
<td>12: <input type="text" size="1" autocomplete="off" name="12"/> </td>
<td>14: <input type="text" size="1" autocomplete="off" name="14"/> </td>
<td>16: <input type="text" size="1" autocomplete="off" name="16"/> </td>
<td>18: <input type="text" size="1" autocomplete="off" name="18"/> </td>
<td>20: <input type="text" size="1" autocomplete="off" name="20"/> </td>
<td>22: <input type="text" size="1" autocomplete="off" name="22"/> </td>
</tr>
</table>
I need to multiply the value that is inputted in the input box by 65 and generate a subtotal in dollars in real time. I've looked around and I'm not too proficient in javascript or jquery so I was wondering if such a solution already existed, or if someone could point me in the right direction in creating one.
using .on and .val() you can get all the values of input . Then you can do what ever operations you want
http://api.jquery.com/on/
http://api.jquery.com/val/
You need to handle the change() event on each input:
$('input').change(function () {
var that = $(this);
that.siblings('div').text(parseInt(that.val(), 10) * 65);
});
http://jsfiddle.net/XZNfS/
Add this to the bottom of your HTML: Subtotal: <span id="subtotal"></span>
Make sure jQuery is loaded, and then toss this JavaScript below the HTML:
<script type="text/javascript">
function compute_subtotal() {
var total = 0;
$("input[type=text]").each( function(i,e) {
var value = $(e).val();
if( parseInt(value) > 0 ) total += (65 * parseInt(value));
});
$("#subtotal").html( total );
}
jQuery(document).ready( function() {
$("input[type=text]").change( function() { compute_subtotal(); } );
$("input[type=text]").keyup( function() { compute_subtotal(); } );
});
</script>

Categories

Resources