How to count value in rows cell table - javascript

If I have more than 1 rows where each rows have 3 column with the inputbox , maybe look like this:
<table id="mytable">
<tr>
<td><input value = "1" /></td>
<td><input value = "2" onBlur="goCount(this)" /></td>
<td><input value = "2+1" /></td>
</tr>
<tr>
<td><input value = "3" /></td>
<td><input value = "4" onBlur="goCount(this)" /></td>
<td><input value = "3+4" /></td>
</tr>
counting must be between cell 1 + cell 2 and the result will show in third cell, maybe the function must be like this :
function goCount(btn) {
var x = btn.value;
var y = ??? ;
var z = x + y;
}
but I do not know how to do that, First get the cell 1 as value and put the result on cell 3 but still in each same rows
is there someone who would help me to resolve this, thanks ^^

Here is your solution
Demo
Your code should be like this
<table id="mytable">
<tr>
<td><input value = "1" onBlur="goCount(this)"/></td>
<td><input value = "2" onBlur="goCount(this)" /></td>
<td><input value = "" id="result"/></td>
</tr>
<tr>
<td><input value = "3" /></td>
<td><input value = "4" onBlur="goCount(this)" /></td>
<td><input value = "" /></td>
</tr>
<script type="text/javascript">
function goCount(btn) {
var x = btn.value;
//var y = ??? ;
var res= document.getElementById("result") ;
//alert( res.value);
if(res.value == "") {
res.value = 0 ;
}
res.value = parseInt(res.value) + parseInt(x) ;
}
</script>
Note: Here is one thing you should note, I have used particular ID to return value in that, if you are using this for many rows you should use jQuery to navigate to that element in respective row and print result in it.

Related

How can i use default value in javascript

<td><input size="12" type="text" name="invoice[promcode][]" /></td>
<td><input size="12" onchange='bitExtention(0)' id="itemname0" type="text" name="invoice[itemname][]"/></td>
<td><input type="number" name="invoice[basecode][]"/></td>
<td><input size="12" type="text" name="invoice[mm][]"/></td>
<td><input onchange='bitExtention(0)' type="number" id="posotita0" name="invoice[quantity][]"/></td>
<td><input onchange='bitExtention(0)' type="number" id="timi0" name="invoice[price][]" step="0.01"/></td>
<td><input onchange='bitExtention(0)' type="number" id="discount0" name="invoice[discount][]" step="0.01"/></td>
<td><input onchange='bitExtention(0)' type="number" id="sum0" name="invoice[sum][]" step="0.01"/></td>
<td><input onchange='bitExtention(0)' type="number" id="foros0" name="invoice[tax][]" step="0.01"/></td>
i want to put a default value for each var like
var timi = document.getElementById("timi"+x.toString()).defaultValue = 50;
this seams to work but when i run the program i change the value to 100 but var timi dont get updated and stuck to 50
function bitExtention(x)
{
var itemname = document.getElementById("itemname"+x.toString()).value;
var test = JSON.parse('<%= raw Item.select('itemName','promCode','baseCode','monadaMe','price','fpa').collect { |p| [p.itemName, p.promCode, p.baseCode, p.monadaMe, p.price, p.fpa] }.join("\n").gsub("\n", " ").split(" ")%>');
var dokimi = test.indexOf(itemname);
var maura = test[dokimi+4];
var posotita = document.getElementById("posotita"+x.toString()).value;
var timi = document.getElementById("timi"+x.toString()).defaultValue = 50;
var sum= document.getElementById("sum"+x.toString()).value;
var fpa= document.getElementById("foros"+x.toString()).value;
var discount= document.getElementById("discount"+x.toString()).value /100;
var total = timi - (timi * discount);
var total_foros = timi*fpa/100;
sum = total * posotita + total_foros
document.getElementById("sum"+x.toString()).value = sum;
}
i just notices tha the 0 || 50 works but it's no visibale at html table
fixed while puting this at the bottom of the code document.getElementById("timi"+x.toString()).value = timi; looks wrong but works for now
You can do
let myVar = document.getElementById(...).value || "default value";
Javascript default parameter
Mozila mdn firefox for default parameter

Adding values to existing array of arrays

I'm making an array that will look like this var qwe = [[a,b],[c],[d]] with the purpose of a and b being the identifiers.
a - d are coming from reading the DOM. My current JS is doing what I want it to but I want to combine the similar arrays by their identifiers. Running the below code will give me
qwe =[
[100,200],[3],[2],
[200, 300],[12],[4],
[100,200],[2],[6]
]
but I want the final array to add the similar arrays by their identifiers so it will end up looking like (based on previous example)
qwe =[
[100,200],[5],[8],
[200, 300],[12],[4]
]
HTML
<table name="tab" id="tab">
<tr>
<th>ID</th>
<th>Location</th>
<th>Value</th>
<th>Other</th>
</tr>
<tr>
<td><input name="itinValue" value="100"></td>
<td><input name="location" value="200"></td>
<td><input name="num" value='3'></td>
<td><input name="other" value='2'></td>
</tr>
<tr>
<td><input name="itinValue" value="200"></td>
<td><input name="location" value="300"></td>
<td><input name="num" value='12'></td>
<td><input name="other" value='4'></td>
</tr>
<tr>
<td><input name="itinValue" value="100"></td>
<td><input name="location" value="200"></td>
<td><input name="num" value='2'></td>
<td><input name="other" value='6'></td>
</tr>
</table>
JS
var table = document.querySelectorAll('[name="itinValue"]');
var qwe = [];
for(var i = 0; i < table.length; i++) {
var a = document.getElementsByName('itinValue')[i].value;
var b = document.getElementsByName('location')[i].value;
var c = document.getElementsByName('num')[i].value;
var d = document.getElementsByName('other')[i].value;
var x = [[a,b],[c],[d]];
//Compare,find,add here
//if identifiers do not exist
qwe.push(x);
}
This is a fiddle to my example that also correctly outputs the html too https://jsfiddle.net/3oge7wxg/125/
It looks like you want something called an associative array, "dict" in python, a key/value pairing, with the keys being your [a,b] part and the values your [c,d] parts.
You can emulate this in JavaScript through objects.
Further reading is here:
JavaScript Associative Arrays Demystified
JavaScript Basics: How to create a Dictionary with Key/Value pairs
I would use objects, just create a composite key:
var table = document.querySelectorAll('[name="itinValue"]');
var qwe = {};
for(var i = 0; i < table.length; i++) {
var a = document.getElementsByName('itinValue')[i].value;
var b = document.getElementsByName('location')[i].value;
var c = new Number(document.getElementsByName('num')[i].value);
var d = new Number(document.getElementsByName('other')[i].value);
var key = a + "_" + b;
previousValue = qwe[key];
qwe[key] = previousValue ? [previousValue[0] + c, previousValue[1] + d] : [c, d];
}
You can convert to your desired array like so:
Object.keys(qwe).map(key => [key.split("_")].concat(qwe[key]));
https://jsfiddle.net/3oge7wxg/161/
Edit: Number constructors; Added fiddle
There are key facts I am taking note of in your question:
you are looping an array of data.
you are storing data based on a key which is a tuple.
values where key is a match is an addition option.
a,b,c,d are all ints,so if these are strings, you would need to run parseint() if they are strings. This can be done by checking if it is currently type is a string, and if so, convert it.
Since it is a tuple and those are not implmented in javascript, you can do something like this.
var m = {};
var table = document.querySelectorAll('[name="itinValue"]');
for(var i = 0; i < table.length; i++) {
var a = +document.getElementsByName('itinValue')[i].value;
var b = +document.getElementsByName('location')[i].value;
var c = +document.getElementsByName('num')[i].value;
var d = +document.getElementsByName('other')[i].value;
var key = a.toString() + "-" + b.toString();
//creates key = "100-200"
if (m[key]){
m[key] = [m[key][0] + c, m[key][1] + d]
}else{
m[key] = [c,d]
}
}
in the end, your map will now have unique keys and a map that looks like:
{
"100-200": [5,8],
"200-300": [12,4]
}
and if for whatever reason, you need to break up they keys later, you just split on the key. map.keys[index].split("-")
I think this is clean, but if you want to go a bit more, you could turn it into a class.
You then store the information in qwe. If you need to, you can easily convert that from a map to a list, but it depends on your desired implementation goal. The key difference generally is whether or not you wish to maintain order. qwe is populated only with this information, and given your comment based on this being your implementation not the best one, it gives me enough insight to believe that order isnt really as important as preservation of they key data elements, this key/tuple, and 2 values.
If you know the amount of fields per row, here is an alternate way of retrieving your array.
var qwe = {};
var els = document.querySelectorAll('table#tab input');
for (i=0; i<els.length; i+=4) {
var indexer = i < 4 ? 0 : i;
var row = {
a: [
parseInt(els[indexer].value)
, parseInt(els[indexer+1].value)
]
, c: parseInt(els[indexer+2].value)
, d: parseInt(els[indexer+3].value)
};
row.key = row.a.join('_');
if (qwe[row.key]) {
qwe[row.key][1][0]+=row.c;
qwe[row.key][2][0]+=row.d;
} else {
qwe[row.key] = [row.a, [row.c], [row.d]];
}
}
console.log( Object.values(qwe) );
You could try to find the item for updating and if not push the new array.
var table = document.querySelectorAll('[name="itinValue"]'),
qwe = [],
a, b, c, d, i,
item;
for (i = 0; i < table.length; i++) {
a = +document.getElementsByName('itinValue')[i].value;
b = +document.getElementsByName('location')[i].value;
c = +document.getElementsByName('num')[i].value;
d = +document.getElementsByName('other')[i].value;
item = qwe.find(([[l, r]]) => l === a && r === b);
if (item) {
item[1][0] += c;
item[2][0] += d;
} else {
qwe.push([[a, b], [c], [d]]);
}
}
console.log(qwe);
<table name="tab" id="tab">
<tr>
<th>ID</th>
<th>Location</th>
<th>Value</th>
<th>Other</th>
</tr>
<tr>
<td><input name="itinValue" value="100"></td>
<td><input name="location" value="200"></td>
<td><input name="num" value='3'></td>
<td><input name="other" value='2'></td>
</tr>
<tr>
<td><input name="itinValue" value="200"></td>
<td><input name="location" value="300"></td>
<td><input name="num" value='12'></td>
<td><input name="other" value='4'></td>
</tr>
<tr>
<td><input name="itinValue" value="100"></td>
<td><input name="location" value="200"></td>
<td><input name="num" value='2'></td>
<td><input name="other" value='6'></td>
</tr>
</table>
Version with Map.
var table = document.querySelectorAll('[name="itinValue"]'),
qwe = [],
a, b, c, d, i,
item
map = new Map;
for (i = 0; i < table.length; i++) {
a = +document.getElementsByName('itinValue')[i].value;
b = +document.getElementsByName('location')[i].value;
c = +document.getElementsByName('num')[i].value;
d = +document.getElementsByName('other')[i].value;
item = map.get([a, b].join('|'));
if (item) {
item[1][0] += c;
item[2][0] += d;
} else {
item = [[a, b], [c], [d]]
map.set([a, b].join('|'), item);
qwe.push(item);
}
}
console.log(qwe);
<table name="tab" id="tab">
<tr>
<th>ID</th>
<th>Location</th>
<th>Value</th>
<th>Other</th>
</tr>
<tr>
<td><input name="itinValue" value="100"></td>
<td><input name="location" value="200"></td>
<td><input name="num" value='3'></td>
<td><input name="other" value='2'></td>
</tr>
<tr>
<td><input name="itinValue" value="200"></td>
<td><input name="location" value="300"></td>
<td><input name="num" value='12'></td>
<td><input name="other" value='4'></td>
</tr>
<tr>
<td><input name="itinValue" value="100"></td>
<td><input name="location" value="200"></td>
<td><input name="num" value='2'></td>
<td><input name="other" value='6'></td>
</tr>
</table>

PHP generated html text box to calculate amt=qty* price

$res=mysql_query($qry);
while($row= mysql_fetch_array($res))
{
echo "<tr><td>".$row['Food_Name']."</td>
<td>".$row['Price']."</td>
<td><input type='text' name='qty". $row['code']."[]' size='2'/></td>
<td><input type='text' name='amt". $row['code']."[]' size='2'/></td>
</tr>
}
I have write this code to display the food_name and price, and display two textboxes for qty and amt.
Now I need to calculate price*qty and display the result in amt box.
please help., javascript, php, ajax, jquery anything only the result should appear. The table is displaing on a popupoverlay jquery.
<tr>
<td>Mutton Kasha</td>
<td>250</td>
<td><input type='text' name='qtySPJ1[]' size='2'/></td>
<td><input type='text' name='amtSPJ1[]' size='2'/></td>
</tr>
<tr>
<td>Mutton Butter Masala</td>
<td>850</td>
<td><input type='text' name='qtySPJ1[]' size='2'/></td>
<td><input type='text' name='amtSPJ1[]' size='2'/></td>
</tr>
This will give you a basic idea of what you can do:
$('input.qty').change(function(){
var $tr = $(this).closest('tr');
var price = parseFloat($tr.find('td').eq(1).text());
var amt = parseInt($(this).val());
$(this).closest('tr').find('input.amt').val(amt * price);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/hfakf6zr/1/
This listens for changes to inputs with class="qty" and updates the amount accordingly.
It's pretty easy. You can do something like this:
PHP Code
$res=mysql_query($qry);
while($row= mysql_fetch_array($res)){
echo "<tr><td>".$row['Food_Name']."</td>
<td class=\"price\">".$row['Price']."</td>
<td><input type='text' class=\"qty\" name='qty". $row['code']."[]' size='2'/></td>
<td><input type='text' class=\"amt\" name='amt". $row['code']."[]' size='2'/></td>
</tr>
}
Now in your jQuery. Add this:
$(document).ready(function(){
var qty = $("input.qty"),
price;
qty.on("input", function(){
var $this = $(this);
price = +($this.closest("td").siblings("td.price").text());
$this.closest("td").siblings("td.amt").val(price*(+$this.val()));
});
});
You can also use other events such as Blur. Hope that works :)
try this
function multiply() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}

Adding up inputs doesn't change javascript

I am trying to add up 3 input elements of type number. This doesn't work for some reason. When I take out the if statements, it works, but only after I change the first one (score1). When I change the others, nothing happens. Thanks.
function getTotal() {
var score1 = document.getElementById("score1");
var score2 = document.getElementById("score2");
var score3 = document.getElementById("score3");
var sc1 = parseInt(score1.value);
var sc2 = parseInt(score2.value);
var sc3 = parseInt(score3.value);
if (isNan(sc1)) {
sc1 = 0;
}
if (isNan(sc2)) {
sc2 = 0;
}
if (isNan(sc3)) {
sc3 = 0;
}
var total = sc1 + sc2 + sc3;
document.getElementById("totalScore").innerHTML = total;
}
function assign() {
var score1 = document.getElementbyId("score1");
var score2 = document.getElementbyId("score2");
var score3 = document.getElementbyId("score3");
score1.onchange = getTotal;
score2.onchange = getTotal;
score3.onchange = getTotal;
}
<!DOCTYPE html>
<html>
<head>
<script src="getTotal.js" type="text/javascript"></script>
</head>
<body>
<header>
<tbody>
<tr>
<td>
Total:
<output id="total" class="totalScore"></output>
</td>
</tr>
</tbody>
</header>
<table>
<tbody>
<td>Score 1</td>
<td><input type="number" id="score1"/></td>
<td>Score 2</td>
<td><input type="number" id="score2" /></td>
<td>Score 3</td>
<td><input type="number" id="score3" /></td>
</tbody>
</table>
<script type="text/javascript">assign();</script>
</body>
</html>
Spelling mistake.
var score1 = document.getElementbyId("score1");
var score2 = document.getElementbyId("score2");
var score3 = document.getElementbyId("score3");
If you check your console you will see the error Uncaught TypeError: undefined is not a function on the line where you are calling score1. The selector is document.getElement*By*Id, you were writing by lowercase..
Your <output> has an id attribute with the value is "total" whereas your class attribute' value is "totalscore". Consider changing the id value to "totalscore" or change getElementById's value to"score"

js - how to default to a specific value if target value does not met

I'm sorry to post this question but I'm kinda newbie when it comes to js. I have created a simple page that will compute charging transactions, so what it will do is to simply multiply the Quantity and Price to .25%. But here is the trick, if the total product is less than 50 the Charge field should default to 50 and that's where I'm kinda lost,
here is my code:
<tr>
<td width="144">Quantity:</td>
<td width="63"><input type="text" name="quantity" id="quantity" size="8"/></td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" size="8"/></td>
</tr>
<tr>
<td colspan="4"><strong>Charges:</strong></td>
</tr>
<tr>
<td>Charge:</td>
<td><input style="color:#F00" type="text" name="charge" id="charge" size="8" readonly="readonly" /></td>
<td colspan="2">Quantity x Price x .25% OR 20 whichever is higher</td>
</tr>
here is the js that i managed to have,
$(function () {
$("#quantity, #price").keyup(function () {
var q = parseFloat($("#quantity").val()); // Quantity
var p = parseFloat($("#price").val()); // Price
if (isNaN(q) || isNaN(p) || q<=0 || p <= 0) {
$("#charge").val('');
return false;
}
$("#charge").val((q * p * 0.0025).toFixed(3)); // Charge
});
});
Put the total in a variable and test it before putting it into the DOM:
$(function () {
$("#quantity, #price").keyup(function () {
var q = parseFloat($("#quantity").val()); // Quantity
var p = parseFloat($("#price").val()); // Price
if (isNaN(q) || isNaN(p) || q<=0 || p <= 0) {
$("#charge").val('');
return false;
}
var total = q * p * 0.0025;
if (total < 50) {
total = 50;
}
$("#charge").val(total.toFixed(3)); // Charge
});
});
Another way is to use Math.max():
$("#charge").val(Math.max(50, q * p * 0.0025).toFixed(3)); // Charge

Categories