javaScript multiply two numbers and show the result into third html input - javascript

I am trying to take a number from my html form and then multiply it with a number from my JavaScript function and displaying the result in another html input. Want I want is when the user click on the result input area then only the multiplication result shows.
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("km").value;
var z = 14;
var x = y * z;
document.getElementById("bill").innerHTML = x;
}
<table>
<tr>
<td>Total Kms Run</td>
<td><input type="text" id="km" name="km" required>
</tr>
<tr>
<td>Total Bill</td>
<td><input type="text" id = "bill" name="bill" required onclick="myFunction()">
</tr>
</table

You're adding the numbers, not multiplying them :).
That aside, inputs don't have innerHTML, you need to set the value:
document.getElementById("bill").value = x;

Do Change like this
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("km").value;
var z = 14;
var x = y * z;
document.getElementById("bill").value = x;
}</script>

You have made many syntax mistakes in html
function myFunction() {
var y = document.getElementById("km").value;
var z = 14;
var x = Number(y) * Number(z);
document.getElementById("bill").value = x;
}
<table>
<tr>
<td>Total Kms Run</td>
<td><input type="text" id="km" name="km" required ></td>
</tr>
<tr>
<td>Total Bill</td>
<td><input type="text" id="bill" name="bill" required onclick="myFunction()"></td>
</tr>
</table>

Related

Using JavaScript to add new row to table but how to I set the variables to be unique if I clone?

I have a button that the user clicks on to add a new row to the bottom of an input table. I would like this to also increment the id. So the next row would have desc2, hours2, rate2 and amount2 as the id. Is there a way to do this in the JavaScript function.
Also - just want to check my logic on this. After the user completes the filled out form, I will be writing all the data to a mysql database on two different tables. Is this the best way to go about this? I want the user to be able to add as many lines in the desc_table as they need. If this is the correct way to be going about this, what is the best way to determine how many lines they have added so I can insert into the db table using a while loop?
JS file:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
HTML:
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Thank you!
Check this code.After appending the row it counts the number of rows and and then assigns via if condition and incremental procedure the id's:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
for(var i=1;i<rows.length;i++){
if(rows[i].children["0"].children["0"].id.match((/desc/g))){
rows[i].children["0"].children["0"].id='desc'+i;
}
if(rows[i].children["1"].children["0"].id.match((/hours/g))){
rows[i].children["1"].children["0"].id='hours'+i;
}
if(rows[i].children["2"].children["0"].id.match((/rate/g))){
rows[i].children["2"].children["0"].id='rate'+i;
}
if(rows[i].children["3"].children["0"].id.match((/amount/g))){
rows[i].children["3"].children["0"].id='amount'+i;
}
}
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Please change variable names for more descriptive. :)
Example solution...
https://jsfiddle.net/Platonow/07ckv5u7/1/
function new_line() {
var table = document.getElementById("desc_table");
var rows = table.getElementsByTagName("tr");
var row = rows[rows.length - 1];
var newRow = rows[rows.length - 1].cloneNode(true);
var inputs = newRow.getElementsByTagName("input");
for(let i=0; i<inputs.length; i++) {
inputs[i].id = inputs[i].name + rows.length;
}
var textarea = newRow.getElementsByTagName("textarea")[0];
textarea.id = textarea.name + rows.length;
table.appendChild(newRow);
}
Note that I removed/edited below fragment.
x.style.display = "";
r.parentNode.insertBefore(x, r);
You could do this a lot easier with jquery or another dom manipulation language, but with vanilla JS here's an example of simply looping through the new row's inputs & textarea and incrementing a counter to append.
var count = 1;
function new_line() {
count++;
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
// update input ids
var newInputs = Array.from(x.getElementsByTagName('input'))
.concat(Array.from(x.getElementsByTagName('textarea')));
newInputs.forEach(function(input) {
var id = input.getAttribute('id').replace(/[0-9].*/, '');
input.setAttribute('id', id + count);
});
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>

Jquery : Product between 2 lists of inputs into a 3rd list

I don't have much experience in jQuery, I'm facing the following challenge
I have the following table
<table>
<thead>
<tr>
<td>Qty</td>
<td>Description</td>
<td>Unit Price</td>
<td>Total Price</td>
<tr>
</thead>
<tbody>
<tr id="itemRow">
<td><input type="text" name="quantity"/></td>
<td><input type="text" name="description"/></td>
<td><input type="text" name="unitPrice"/>/td>
<td><input type="text" name="totalPrice"/></td>
<tr>
</tbody>
</table>
<input type="text" name="total"/>
Additionally, I'm able to clone #itemRow as many times as required, enlarging the amount of items.
The idea is to calculate the total price for each row (by quantity * unitPrice) and assign it to totalPrice. And assign the sum of totalPrice to total.
This is the javascript I'm using, but I get an error that says "cantidades[i].val() is not a function"
function calculate(){
var $total = $('#total');
var $cantidades = $('input[name=quantity]')
var $unitarios = $('input[name=unitPrice]')
var $totales = $('input[name=totalPrice]')
var len = $cantidades.length;
$total.val(0);
for (var i = 0; i < len; i++){
// calculate total for the row. ERROR HERE!
$totales[i].val($cantidades[i].val() * $unitarios[i].val());
// Accumulate total
$total.val($totalExento.val() + $totales[i].val());
}
}
What am I missing? I think I'm not getting "jQuery objects" from the selector but I'm not sure hot to do this.
Thanks in advance!
This line: var $cantidades = $('input[name=quantity]') retrieves a jQuery instance that cannot be accessed like you did with $cantidades[i].
Fix it like this:
var singleElementCantidades = $($cantidades[i]);
singleElementCantidades.val();
What happened is that $('input[name=quantity]') retrieves an array that is an instance of jQuery. And when you access its content by using cantidades[i] you are not managing a jQuery instance anymore, you are accessing something else wich doesn't have the definition of val.
$cantidades would give you a jquery object however by using index or 'get' property would actually give you the equivalent javascript object. So in your case, you would need to use $cantidades[i].value. instead of $cantidades[i].val().
for (var i = 0; i < len; i++){
$totales[i].value = $cantidades[i].value * $unitarios[i].value;
$total.val($totalExento.val() + $totales[i].value);
}
I think you cannot globally get $('input[name=quantity]'), $('input[name=unitPrice]') and $('input[name=totalPrice]').
You should identify them for each row.
Here a example on jsfiddle
<table>
<thead>
<tr>
<td>Qty</td>
<td>Description</td>
<td>Unit Price</td>
<td>Total Price</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="quantity"/></td>
<td><input type="text" name="description"/></td>
<td><input type="number" name="unitPrice"/></td>
<td><input type="number" name="totalPrice"/></td>
</tr>
</tbody>
</table>
<button type="button" id="addRow">addRow</button>
<button type="button" id="calculate">calculate</button>
<input type="number" name="total" id="total"/>
The js part:
$(document).ready(function () {
var $total = $('#total');
var $addRow = $('#addRow');
var $calculate = $('#calculate');
var $emptyRow = $('tbody tr').clone();
var $body = $('tbody');
$addRow.on('click', function () {
$body.append($emptyRow.clone());
});
$calculate.on('click', function () {
var total = 0;
$body.find('tr').each(function () {
var $row = $(this);
var q = Number($row.find('[name=quantity]').val());
var p = Number($row.find('[name=unitPrice]').val());
var subTotal = q * p;
$row.find('[name=totalPrice]').val(subTotal)
total += subTotal;
});
$total.val(total);
})
});

Multiple x number from user-input using for-loop or while-loop?

I have 2-column table. 1st row from the left table show label "Enter X (Number)" and input field type="number" next to it. 2nd row "Show X" for how much Multiple X will be displayed, and the 3rd row for output/result.
Example:
User-Input
Enter X(number): 10
Show X : 7
Result (output)
10, 20, 30, 40, 50, 60, 70
how to do this with for-loop?
how to do this using while-loop with the same result?
<html>
<head>
<script>
function showValues() {
var num1 = document.getElementById("input1").value;
var num2 = document.getElementById("input2").value;
var outputString = "" + (num1);
for (var count = 2; count <= num2; count++) {
outputString += ", " + (num1 * count);
}
document.getElementById("theAnswer").value = outputString;
}
</script>
</head>
<body>
<div>
<table id="tableid">
<tr>
<td>Enter X(number):</td> <td><input id="input1"></td>
</tr>
<tr>
<td>Show X:</td> <td><input id="input2" ></td>
</tr>
<tr>
<td> answer </td> <td><input id="theAnswer" ></td>
</tr>
</table>
<br/>
<button type="button" onclick="showValues();">showValues<br/>
</div>
</body></html>

HTML - Invoice: How to add values to text field and calculate total

I was able to create the template, but I'm not sure what to do from here.
When I click my add item button, I want the values to go into the text area I created on the bottom and change the subtotal and total as I keep adding items.
<html>
<head>
<meta charset = "utf-8">
<h1>Invoice Manager</h1>
<style type "text/css">
div {position: absolute;
top: 200px;
left: 90px;
z-index: 1;}
</style>
<script type = "text/javascript">
</script>
</head>
<body>
<table>
<tr>
<td align="right">Item Code:</td>
<td align="left"><input type="text" name="code" /></td>
</tr>
<tr>
<td align="right">Item Name:</td>
<td align="left"><input type="text" name="itemName" /></td>
</tr>
<tr>
<td align="right">Item Cost:</td>
<td align="left"><input type="text" name="cost" /></td>
</tr>
<tr>
<td align="right">Quantity:</td>
<td align="left"><input type="text" name="quantity" /></td>
</tr>
</table>
<div id="AddItemButton">
<td align = "left"><input type="submit" name="Submit" value="Add Item"></td>
</div>
</form>
<br></br> <br></br>
<font size = "5">Current Invoice</font>
<hr style = "height:2px;border:none;color:#333;background-color:#333;"></hr>
<p><label> <br>
<textarea name = "textarea"
rows = "12" cols = "180"></textarea>
</label></p>
<form>
<table>
<tr>
<td align="right">Subtotal:</td>
<td align="left"><input type="text" name="subtotal" /></td>
</tr>
<tr>
<td align="right">Sales Tax:</td>
<td align="left"><input type="text" name="tax" /></td>
</tr>
<tr>
<td align="right">Total:</td>
<td align="left"><input type="text" name="total" /></td>
</tr>
</table>
</form>
<form>
<input type = "button" value = "Add Item" onclick="textarea"/> <input type = "text" id = "cost" size ="20" />
</form>
That's what I have as a template. When I type in Item Code, Item Name, Item Cost and Quantity in those fields, I'd like those values to go in the text area on the bottom. I imagine I would need to write something in the script.
I'm not sure how to achieve this, but I was thinking that the first batch of info the user adds could equal a variable like a
Then the second values inputted could equal b
So let's say the user adds 3 items.
total = (a + b + c)
Or something like that.
Here's an example of what one "Add Item" would do. I'd like these submissions to appear in the text field I created like so
---Item Code--- ---Item Name--- ---Item Cost--- ---Quantity---
3 Dell 499 1
Any ideas on what I could do? I'm at a loss
Thanks
EDIT: I'm adding my script, I'm wondering if there's something wrong with it
<script type = "text/javascript">
function computeCost(){
var code = document.getElementById("code").value;
var a = code; // item code
var itemName = document.getElementById("itemName").value;
var b = itemName; // item name
var cost = document.getElementById("cost").value;
var c = cost; // calculate cost
var quantity = document.getElementById("quantity").value;
var d = quantity; // calculate quantity of items
var subtotal = document.getElementById("subtotal").value;
var e = c * d; // multiplying cost by quantity = subtotal
var tax = document.getElementById("tax").value;
var f = e * .7; // multiplying subtotal by tax(.7) = amount of tax owed
var total = document.getElementById("total").value;
var g = f + e; //adding tax to subtotal = total value
document.getElementByID("yo").value = total;
}
function clear()
{
document.getElementById("a","b","c","d", "e", "f", "g").reset();
} // end of clear
</script>
I dont have much time to give a polished script, but this provides basic functionality
EDIT: added script tags and basic JQUERY things
note that because of loading JQUERY from the internet, it wont work without internet connection, if you wish to use it without internet con, download the script and link it locally
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type = "text/javascript">
$(function(){
var textContent = $('textarea').val();
var textRow = "";
$('input[type=submit]').click(function(){
$('input[type=text]').each(function(){
textRow = textRow+$(this).val()+'\t';
});
textContent = textContent + '\n' + textRow;
textRow = "";
$('textarea').val(textContent);
});
});
</script>
this is just the necessary JS and HTML, nothing fancy:
function id(id){return document.getElementById(id);}
var val1 = 0;
var val2 = 0;
function val(){
val1 = parseInt(id("t1").value);
val2 = parseInt(id("t2").value);
id("total").innerHTML = ((val1 > 0 && val2 > 0))? val1 * val2 : 0;
}
<input id="t1" onkeyup="val()" type="number">
<input id="t2" onkeyup="val()" type="number">
<h1 id="total"></h1>

Passing function results to another function variable in Javascript

Please forgive my ignorance, as I'm pretty new to Java script. Here is what I'm trying to do. I have a form where users can enter in data to get reimbursed. It sums totals up horizontally, and then takes the final values and adds them vertically for a grand total.
I have everything working horizontally, and I can add the last 5 rows vertically, but when I add in the first two rows, it doesn't work. I get NaN for the answer. Here is the code.
<script type="text/javascript">
function calcWages(){
document.getElementById('wages').innerHTML = '';
var num2 = new Number(document.getElementById('hours').value);
var num3 = new Number(document.getElementById('rate').value);
document.getElementById('wages').innerHTML = ((num3 * num2).toFixed(2));
}
function calcMilage(){
document.getElementById('milage').innerHTML = '';
var num4 = new Number(document.getElementById('miles').value);
document.getElementById('milage').innerHTML = ((num4 * .555).toFixed(2));
}
function calcTotal(){
document.getElementById('total').innerHTML = '';
var num5 = new Number(document.getElementById('wages').value);
var num6 = new Number(document.getElementById('milage').value);
var num7 = new Number(document.getElementById('travel').value);
var num8 = new Number(document.getElementById('lodging').value);
var num9 = new Number(document.getElementById('food').value);
var num10 = new Number(document.getElementById('office').value);
var num11 = new Number(document.getElementById('other').value);
document.getElementById('total').innerHTML = (( num5 + num6 + num7 + num8 + num9 + num10 + num11).toFixed(2));
}
window.onload=function(){
document.getElementById('totalCalc').onclick = calcTotal;
}
</script>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td>
Total:
</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>Wages:</td>
<td>Hours:(8 a day Max)<input type="text" name="hours" id="hours" size="3" maxlength="3" onchange="calcWages()"></td>
<td>Rate:<input type="text" name="rate" id="rate" size="3" maxlength="5" onchange="calcWages()"></td>
<td>=</td>
<td><div id="wages"></div></td>
</tr>
<tr>
<td>Milage:</td>
<td>Miles<input type="text" name="miles" id="miles" size="3" maxlength="4" onchange="calcMilage()"></td>
<td>IRS rate ($0.555)</td>
<td>=</td>
<td><div id="milage"></div></td>
</tr>
<tr>
<td>
Travel: </td>
<td colspan="2">
<input type="text" name="tavelitem" id="travelitem" size="36"> </td>
<td>
=
</td>
<td><input type="text" name="travel" id="travel" size="3"> </td>
</tr>
<tr>
<td>Lodging:</td>
<td colspan="2"><input type="text" name="lodgingitem" id="lodgingitem" size="36"> </td>
<td>=</td>
<td><input type="text" name="lodging" id="lodging" size="3"></td>
</tr>
<tr>
<td>Food:</td>
<td colspan="2"><input type="text" name="fooditem" id="fooditem" size="36"> </td>
<td>=</td>
<td><input type="text" name="food" id="food" size="3"></td>
</tr>
<tr>
<td>Office Supplies:</td>
<td colspan="2"><input type="text" name="officesupplies" id="officesupplies" size="36"> </td>
<td>=</td>
<td><input type="text" name="office" id="office" size="3"></td>
</tr>
<tr>
<td>Other:</td>
<td colspan="2"><input type="text" name="otheritem" id="otheritem" size="36"></td>
<td>=</td>
<td><input type="text" name="other" id="other" size="3"></td>
</tr>
<tr>
<td></td>
<td><button id="totalCalc">Total</button></td>
<td>Grand Total:</td>
<td>=</td>
<td><div id="total"></div></td>
</tr>
</table>
The calcWages function and the calcMilage functions work, but I seem to be getting hung up and getting the results of those two, to work in the calcTotal function. I apologize if this doesn't make sense. Let me know, and I'll try to clarify. Thanks.
Here you're setting the .innerHTML
document.getElementById('milage').innerHTML = ((num4 * .555).toFixed(2));
// ^^^
But then you're getting the .value from the same element.
var num6 = new Number(document.getElementById('milage').value);
// ^^^
Seems like you should be using one or the other. If the .innerHTML works for the first, then you should fetch it as well, or vice versa (unless perhaps this is a textarea element).
Either that, or you intended to use the miles element instead of milage.
var num6 = new Number(document.getElementById('miles').value);
// ^^^
They functions don't return anything, so you cannot really get their results. However, you can just call them inside calcTotal:
function calcTotal(){
calcWages();
calcMilage();
// ...
}
From my comment: When you see yourself using variables names with a running index, using an array and/or a loop is likely to be a better solution.
Without changing your HTML, a cleaner solution would be:
var fields = ['wages', 'milage', ...];
function calcTotal(){
var sum = 0;
for (var i = 0; i < fields.length; i++) {
sum += +document.getElementById(fields[i]).value
}
document.getElementById('total').innerHTML = sum.toFixed(2);
}
You can also give the elements a common class to avoid listing their IDs in an array.
<script type="text/javascript">
function calcWages(){
document.getElementById('wagestotal').innerHTML = '';
var hours = new Number(document.getElementById('hours').value);
var rate = new Number(document.getElementById('rate').value);
document.getElementById('wagestotal').innerHTML = ((hours * rate).toFixed(2));
}
function calcMilage(){
document.getElementById('milagetotal').innerHTML = '';
var miles = new Number(document.getElementById('miles').value);
document.getElementById('milagetotal').innerHTML = ((miles * .555).toFixed(2));
}
function calcTotal(){
document.getElementById('total').innerHTML = '';
var wages = new Number(document.getElementById('wagestotal').innerHTML);
var milage = new Number(document.getElementById('milagetotal').innerHTML);
var travel = new Number(document.getElementById('travel').value);
var lodging = new Number(document.getElementById('lodging').value);
var food = new Number(document.getElementById('food').value);
var office = new Number(document.getElementById('office').value);
var other = new Number(document.getElementById('other').value);
document.getElementById('total').innerHTML = ((wages + milage + travel + lodging + food + office + other).toFixed(2));
}
window.onload=function(){
document.getElementById('totalCalc').onclick = calcTotal;
}
</script>
So this is the final script. I changes the names of the variables to things that make sense. The final hand up I was having was being able to ad the totals form the wages function, and the milage function into the the grand total. The part I had messed up was that I had:
var wages = new Number(document.getElementById('wagestotal').value);
var milage = new Number(document.getElementById('milagetotal').value);
Instead of:
var wages = new Number(document.getElementById('wagestotal').innerHTML);
var milage = new Number(document.getElementById('milagetotal').innerHTML);
in the calcTotal funciton. The user can enter stuff in to the form that this ties to, and it all gets totaled like it should. Thanks again for helping focus my thoughts.

Categories