How to get a table data element using the id? - javascript

I can't seem to grab the inner text of an element. I have tried many approaches to this and still can't fully understand why this is not working.
I have already tried grabbing it by the class, by the id and even by the type of element.
I expected the function to run, but instead it gets caught in the problem areas I marked within the javascript.
function updateCartTotal() {
var cartItemContainer = document.getElementById('cart-table')
var cartRows = cartItemContainer.rows.length
var total = 0
for (var i = 1; i < cartRows; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementById('item-total')[0] //this is the issue ALSO: i have tried removing "[0]"
var quantityElement = cartRow.getElementsByClassName('form-control')[0] //this is the issue ALSO: i have tried removing "[0]"
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total + (price * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}
<table class="table table-striped table-border checkout-table" id="cart-table">
<tbody>
<tr>
<td class="hidden-xs">
<img src="images/intro-04.jpg" alt="[Rainbow Six] Complete Edition" />
</td>
<td>
<h5 class="txt25">[Rainbow Six] Complete Edition</h5>
</td>
<td class="txt25" id="item-total">
$45.00
</td>
<td>
<input class="form-control" type="number" name="" value="1" max="50" min="1" />
</td>
<td class="item-total-total txt25">
$45.00
</td>
<td><button class="btn btn-danger" onclick="removeRow(this)" type="button">REMOVE</button></td>
</tr>
</tbody>
</table>

getElementById is only on document, not other nodes
document.getElementById('item-total') will return ONE element and
IDs must be unique.
I changed <td class="txt25" id="item-total"> to <td class="txt25 item-total">
I also suggest you change class="cart-total-price" to id="cart-total-price" since there is likely only one
Try classes and querySelector which is superior to getElementsByClassName:
function updateCartTotal() {
[...document.querySelectorAll('cart-table tbody tr')].forEach((cartRow) => {
var price = cartRow.querySelector('.item-total').innerText.replace(/[$\s]/g,"")
var quantity = cartRow.querySelector('.form-control').value;
total += (+price * +quantity)
});
document.querySelector('.cart-total-price').innerText = '$' + total.toFixed(2)
}
For older browser support you can change first line to
var cartRows = document.querySelectorAll('cart-table tbody tr')
for (var i=0, cartRow;i<cartRows.length; i++) {
cartRow = cartRows[i];

Related

How to get order total if quantity is updated

Order entry form contains product name, price and quantity columns:
<table id="order-products" class="mobileorder-table">
<colgroup>
<col style="width: 80%;">
<col style="width: 10%;">
<col style="width: 10%;">
</colgroup>
<tbody>
<tr>
<td>
Product1
</td>
<td>
<span class="mobileorder-price">0,98</span>
</td>
<td>
<input data-product="4750211645618" class="quantity" id="product_Soodkogus" name="product.Soodkogus"
type="number" min="0" max="999999" value=""
onblur="orderSumRefresh()" />
</td>
</tr>
</tbody>
</table>
Order total <p id="js-doksumma"></p>
If quantity is changed, order total value should updated. I tried
<script>
function parseFloatFormatted(txt) {
if (typeof txt !== 'string' || txt === null || txt === "") {
return 0
}
return parseFloat(txt.replace(',', '.').replace(' ', ''))
}
function orderSumRefresh() {
let totalAmount = 0
const table = document.getElementById("order-products")
table.rows.forEach((row) => {
//for (let i in table.rows) {
// const row = table.rows[i]
const hind = row.cells[1].querySelector(".mobileorder-price").value
const kogus = row.cells[2].querySelector(".quantity").value
const rowSum = Math.round(parseFloatFormatted(hind)* parseFloatFormatted(kogus) * 100) / 100
totalAmount += rowSum
});
var dok = document.getElementById("js-doksumma")
dok.innerText = totalAmount.toFixed(2)
}
</script>
but got error
How to properly implement this ? Should pure CSS, javascript or query used?
Modern Chrome browser is used in mobile phone, ASP.NET 6 MVC Razor application.
As Nick Vu said a first problem is in the for loop and I changed to:
for (let i = 0; i < table.rows.length; i++) {
I find more problems in the code for example the index of the childNodes is wrong, using
console.log(row.cells[1].childNodes)
you can see there are 3 child and you are searching for the middle one (index: 1)
Then for accessing the data of the input element you need to use the .value property like this:
const kogus = row.cells[2].childNodes[1].value
********************* EDIT *******************
Changing the code as the answer has changed.
For accessing the data of the html element use .innerHTML property.
function parseFloatFormatted(txt) {
if (typeof txt !== 'string' || txt === null || txt === "") {
return 0
}
return parseFloat(txt.replace(',', '.').replace(' ', ''))
}
function orderSumRefresh() {
let totalAmount = 0
const table = document.getElementById("order-products")
/*
for (let i = 0; i < table.rows.length; i++) {
const row = table.rows[i]
const hind = row.cells[1].childNodes[1].innerHTML
const kogus = row.cells[2].childNodes[1].value
const rowSum = Math.round(parseFloatFormatted(hind) * parseFloatFormatted(kogus) * 100) / 100
totalAmount += rowSum
}
*/
for (const row of table.rows) {
const hind = row.cells[1].querySelector(".mobileorder-price").innerHTML
const kogus = row.cells[2].querySelector(".quantity").value
const rowSum = Math.round(parseFloatFormatted(hind)* parseFloatFormatted(kogus) * 100) / 100
totalAmount += rowSum
}
const dok = document.getElementById("js-doksumma")
dok.innerText = totalAmount.toFixed(2)
}
<table id="order-products" class="mobileorder-table">
<colgroup>
<col style="width: 80%;">
<col style="width: 10%;">
<col style="width: 10%;">
</colgroup>
<tbody>
<tr>
<td>
Product1
</td>
<td>
<span class="mobileorder-price">0,98</span>
</td>
<td>
<input data-product="4750211645618" class="quantity" id="product_Soodkogus" name="product.Soodkogus"
type="number" min="0" max="999999" value="" onblur="orderSumRefresh()" />
</td>
</tr>
</tbody>
</table>
Order total <p id="js-doksumma"></p>
I suggest you to use the console.log() and log some variable to see if there is somethink wrong with the code.
Nick is correct. Remember that table.rows is not an array but an HTMLCollection. You can fix the issue simply doing:
const table = document.getElementById("order-products")
for (const row of Array.from(table.rows)) {
}
If you want to see for yourself that there is an "length" property being iterated over, open the dev tools, select the table from the elements tab, and run this snippet in the console:
for (let i in $0.rows) {
console.log(i);
console.log($0.rows[i].cells[0]);
}
You will see the last iteration print "length" and then throw an exception.
Your problem is from here
for (let i in table.rows) {}
The value will be "0" and "length" (not index like your expectation), so it throws an error while trying to access row.cells[0].childNodes (row.cells is undefined)
I'd suggest you modify it to
for (const row of table.rows) {}
The full code can be
function parseFloatFormatted(txt) {
if (typeof txt !== 'string' || txt === null || txt === "") {
return 0
}
return parseFloat(txt.replace(',', '.').replace(' ', ''))
}
function orderSumRefresh() {
let totalAmount = 0
const table = document.getElementById("order-products")
for (const row of table.rows) {
const hind = row.cells[1].childNodes[0].innerHTML
const kogus = row.cells[2].childNodes[0].innerText
const rowSum = Math.round(parseFloatFormatted(hind) * parseFloatFormatted(kogus) * 100) / 100
totalAmount += rowSum
}
const dok = document.getElementById("js-doksumma")
dok.innerText = totalAmount.toFixed(2)
}
<table id="order-products" class="mobileorder-table">
<colgroup>
<col style="width: 80%;">
<col style="width: 10%;">
<col style="width: 10%;">
</colgroup>
<tbody>
<tr>
<td>
Product1
</td>
<td>
<span class="mobileorder-price">0,98</span>
</td>
<td>
<input data-product="4750211645618" class="quantity" id="product_Soodkogus" name="product.Soodkogus" type="number" min="0" max="999999" value="" onblur="orderSumRefresh()" />
</td>
</tr>
</tbody>
</table>
Order total
<p id="js-doksumma"></p>

How do I dynamically change the ID to do calculations?

I have the same form duplicated and triplicated, and depending on clicks on a button, they appear. What I want to do is to be able to make calculations, for example, of the cell Quantity and Unit_Price a multiplication and that the result is reflected in Total Price.
I need the Quantity and Unit_Price IDs to change dynamically so that the result is displayed per cell in their respective Total Price. I already wrote a piece of code that takes the number of each cell, the problem is that I don't know how to put it with the ID so that it is dynamic (the number should change depending on the cell it is in)
This is where I don't know how the code should be:
function multiplicar() {
let quantity = parseInt(document.getElementById('id__form-1-quantity').value);
let unit_price = document.getElementById('id__form-1-unit_price').value;
let total_price = document.getElementById('id__form-1-total_price');
total_price.value = quantity * unit_price;
}
function updateEmptyFormIDs(element, totalForms) {
var thisInput = element
var currentName = element.attr('name')
var newName = currentName.replace(/__prefix__/g, totalForms)
thisInput.attr('name', newName)
thisInput.attr('id', "id__" + newName)
var newFormRow = element.closest(".part-form");
var newRowId = "row_id_" + newName
newFormRow.attr("id", newRowId)
newFormRow.addClass("new-parent-row")
var parentDiv = element.parent();
parentDiv.attr("id", "parent_id_" + newName)
var inputLabel = parentDiv.find("label")
inputLabel.attr("for", "id_" + newName)
return newFormRow
}
function addForm() {
//$('.add-new-form').click(function(e){
var formId = "id_form-TOTAL_FORMS"
var emptyRow = $("#empty-row").clone();
emptyRow.attr("id", null);
var totalForms = parseInt($('#' + formId).val());
var newFormRow;
emptyRow.find("input,select,textarea").each(function() {
newFormRow = updateEmptyFormIDs($(this), totalForms)
})
$(".part-form:last").after(newFormRow)
$('#' + formId).val(totalForms + 1);
}
<table>
<tr>
<td id="parent_id_form-1-quantity">
<input type="number" name="form-1-quantity" class="form-control" id="id__form-1-quantity">
</td>
<td id="parent_id_form-1-unit_price">
<input type="number" name="form-1-unit_price" class="form-control" onchange="multiplicar()" id="id__form-1-unit_price">
</td>
<td id="parent_id_form-1-total_price">
<input type="number" name="form-1-total_price" class="form-control" id="id__form-1-total_price">
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Html table add column with javascript

I am obviously very new to JS. I need to solve a problem where i can't change the HTML and CSS-file. From the HTML-file I am supposed to:
add a column with the header "Sum". (Already did that)
add a row att the bottom with the div id "sumrow". (Did that as well)
add a button at the end. (Did that)
add the total from columns "Price and Amount" into column "Sum" when button is clicked
(This where I am lost)
And like I said I can't change anything in HTML and CSS-files.
// Create a newelement and store it in a variable
var newEl = document.createElement('th');
//Create a text node and store it in a variable
var newText = document.createTextNode('Summa');
//Attach the newtext node to the newelement
newEl.appendChild(newText);
//Find the position where the new element should be added
var position = document.getElementsByTagName('tr')[0];
//Insert the newelement into its position
position.appendChild(newEl);
// Find a <table> element with id="myTable":
var table = document.getElementById("pricetable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(-1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
// Add some text to the new cells:
cell1.innerHTML = "";
cell2.innerHTML = "";
cell3.innerHTML = "";
cell4.innerHTML = sumVal;
cell5.innerHTML = "";
cell6.innerHTML = "";
//Puts divid sumrow
row.setAttribute("id", "sumrow");
var table = document.getElementById("pricetable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
//Creates button
var button = document.createElement("button");
button.innerHTML = "Beräkna pris";
// 2. Append somewhere
var body = document.getElementsByTagName("tbody")[0];
body.appendChild(button);
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
button.setAttribute("class", "btn-primary");
function medelVarde(celler){
var summa = 0;
for(var i = 3; i < celler.length -1; i++){ //Räknar igenom från cell nr 4
var nuvarandeVarde = celler[i].firstChild.nodeValue;
summa = summa + parseInt(nuvarandeVarde);
}
var medel = summa / 1;
return medel;
}
function raknaUtMedelvarde(){
var tabell = document.getElementById("pricetable");
var rader = tabell.getElementsByTagName("tr");
for(var i = 1; i < rader.length; i++){
var tabellceller = rader[i].getElementsByTagName("td"); //Pekar på de td-element som vi har hämtat
var medel = medelVarde(tabellceller);
var medeltext = document.createTextNode(medel);
var medelelement = tabellceller[tabellceller.length - 1];
var row2 = table.insertRow(-1);
medelelement.appendChild(medeltext.cloneNode(true));
.table {
background: white;
}
tr#sumrow {
background-color: #cce4ff;
}
tr#sumrow td:first-child::after{
content: "\a0";
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Handling calculations and tables</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="container">
<div id="header" class="text-center px-3 py-3 pt-md-5 pb-md-4 mx-auto">
<h1 class="display-4">Home Electronics</h1>
<p class="lead">Excellent prices on our hone electronics</p>
</div>
<div id="content">
<table id="pricetable" class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Articlenr</th>
<th>Producttype</th>
<th>Brand</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Telephone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>22256289</td>
<td>Telephone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>24444343</td>
<td>Telephone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- add this script as snippet in this question -->
<!-- <script src="scripts/calculate.js"></script> -->
</body>
</html>
Or code is available on https://jsfiddle.net/cmyr2fp6/
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
For the button click event listener, you don't have to add the medelVarde function.
Also, speaking of that function, I'm not really sure what's happening there. Are you trying to multiply the price and the amount? If so, you can just get the price cell's text and multiply it by the amount input's value (converting to Number the values before multiplying).
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
The [,,, priceCell, amountCell, sumCell] is just a short-hand for getting the cells you want from the row (destructuring assignment. querySelectorAll returns a NodeList wherein you can get the element by index.
function setUp() {
// Set up table.
const table = document.getElementById('pricetable');
const headerRow = table.querySelector('thead tr');
const sumHeader = headerRow.insertCell();
const tbody = table.querySelector('tbody');
const sumTotalRow = tbody.insertRow();
const sumTotalCell = sumTotalRow.insertCell();
sumHeader.innerText = 'Summa';
sumTotalCell.colSpan = '5';
sumTotalCell.innerText = 'Total';
tbody.querySelectorAll('tr').forEach(row => row.insertCell());
// Set up button.
const btn = document.createElement('button');
btn.innerText = 'Beräkna pris';
btn.addEventListener('click', () => {
let total = 0;
tbody.querySelectorAll('tr').forEach((row, i, arr) => {
if (i < arr.length - 1) {
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
sumCell.innerText = sum;
total += sum;
} else {
const totalCell = row.querySelector('td:last-child');
totalCell.innerText = total;
}
});
});
document.body.appendChild(btn);
}
setUp();
Hey ZioPaperone welcome to the JS World :-)
First of all I would recommend to wrap you logic into functions, eg
appendRow() {
//put append row logic here
}
Now let's move on to your question, appending a column is a bit more of a trick then appending a row. You might noticed already that the DOM-Structure is a bit more complex. So for a row you could you correctly has added a node to your tbody.
For a column we need to learn how to create a cell and how we add an entry to the thead. We will use the insertCell() method to insert cells, for thead cells that won't work, so we need to add the th with createElement() and append it with appendChild()
function appendColumn() {
// insertCell doesn't work for <th>-Nodes :-(
var tableHeadRef = document.getElementById('pricetable').tHead; // table reference
var newTh = document.createElement('th');
tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead
newTh.innerHTML = 'thead title';
// open loop for each row in tbody and append cell at the end
var tableBodyRef = document.getElementById('pricetable').tBodies[0];
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var newCell = tableBodyRef.rows[i].insertCell(-1);
newCell.innerHTML = 'cell text'
}
}
EDIT:
To sum up values in col u can use the same approach. I broke down the nodes for better understanding. You also might want to add a check if your table data contains a number with isNaN().
function sumColumn(tableId, columnIndex) {
var tableBodyRef = document.getElementById(tableId).tBodies[0];
var sum = 0; // Initialize sum counter with 0
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var currentRow = tableBodyRef.rows[i]; //access current row
var currentCell = currentRow.cells[columnIndex]; // look for the right column
var currentData = currentCell.innerHTML; // grab cells content
var sum += parseFloat(currentData); // parse content and add to sum
}
return sum;
}

Multiple countdown timers comparing a given time and current time?

Really struggling with this part for some reason.
I'm creating a timer I can use to keep track of bids. I want to be able to compare two times and have the difference (in minutes and seconds) shown in the countdown column. It should be comparing the bid start time and the time right now.
Perhaps when it reaches bid start it could also change to show how long until bid ends. Eventually I want to add background changes once it's getting close to the time, and perhaps the ablility to set alarms with a prompt window.
Here's the code I have so far:
HTML
<table>
<tr>
<td>Item Name</td>
<td><input id="itemNameField" placeholder="" type="text"></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Time of Notice</td>
<td><input id="noticeField" type="time"></td>
</tr>
</table>
<input id="addButton" onclick="insRow()" type="button" value="Add Timer">
<div id="errorMessage"></div>
<hr>
<div id="marketTimerTableDiv">
<table border="1" id="marketTimerTable">
<tr>
<td></td>
<td>Item Name</td>
<td>Time of Notice</td>
<td>Bid Start</td>
<td>Bid End</td>
<td>Countdown</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div id="itembox"></div>Example Item
</td>
<td>
<div id="noticebox"></div>12:52
</td>
<td>
<div id="bidstartbox"></div>13:02
</td>
<td>
<div id="bidendbox"></div>13:07
</td>
<td>
<div id="countdownbox"></div>
</td>
<td><input id="delbutton" onclick="deleteRow(this)" type="button" value="X"></td>
</tr>
</table>
</div>
JAVASCRIPT
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
if (i == 1) {
console.log = "hi";
} else {
document.getElementById('marketTimerTable').deleteRow(i);
}
}
function insRow() {
if (itemNameField.value == "" || noticeField.value == "") {
var div = document.getElementById('errorMessage');
div.innerHTML = "*Please fill in the fields*";
div.style.color = 'red';
document.body.appendChild(div);
} else {
var div = document.getElementById('errorMessage');
div.innerHTML = "";
var x = document.getElementById('marketTimerTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var inp1 = new_row.cells[1].getElementsByTagName('div')[0];
inp1.id += len;
inp1.innerHTML = itemNameField.value;
itemNameField.value = "";
var inp2 = new_row.cells[2].getElementsByTagName('div')[0];
inp2.id += len;
inp2.innerHTML = noticeField.value;
noticeField.stepUp(10);
var inp3 = new_row.cells[3].getElementsByTagName('div')[0];
inp3.id += len;
inp3.innerHTML = noticeField.value;
noticeField.stepUp(5);
var inp4 = new_row.cells[4].getElementsByTagName('div')[0];
inp4.id += len;
inp4.innerHTML = noticeField.value;
var inp5 = new_row.cells[5].getElementsByTagName('div')[0];
inp5.id += len;
inp5.innerHTML = "";
noticeField.value = "";
x.appendChild(new_row);
}
}
I apologize in advance because my code is probably really messy and badly formatted. Here's a JSFIDDLE as well! Thanks :)
To calculate the difference between the current and given time, you can use setInterval
Example :
var noticeTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
var diffInHours = currentDate.getHours() - noticeTime[0];
var diffInMinutes = currentDate.getMinutes() - noticeTime[1];
inp5.innerHTML = diffInHours + ":" + diffInMinutes;
if(diffInHours === 0 && diffInMinutes === 0) {
clearInterval(interval);
}
},1000)
I managed to do it with the help of the code from ProgXx.
I added the following code:
var noticeTime = noticeField.value.split(":");
var originalTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
noticeTime[1] = originalTime[1] - currentDate.getMinutes() + 10;
noticeTime[1] = noticeTime[1] + (originalTime[0] * 60) - (currentDate.getHours() * 60);
Here's a JSFIDDLE of the finihsed code: http://jsfiddle.net/joefj8wb/

percentages when converting sterling to euro

Hi I am trying to convert Sterling to Euros. But I can't seem to get the percentages correct. I have tried it several ways without luck. The idea is to get 1% of the sterling price then multiply it by the conversion rate and add it to the sterling price to make the euro total, and then do the same with vat.
Hope someone can help, thanks!
Here is my code.
var input = document.querySelectorAll('input');
var conversionRate = input[0];
var sterling = input[1];
var vat = input[2];
var euro = input[3];
init();
function init() {
calculateKeyUp();
}
function calculateKeyUp() {
for (var i = 0; i < input.length; i++) {
input[i].addEventListener("keyup", function() {
//var totalLessVat = (sterling.value) + (conversionRate.value * (sterling.value / 100));
var sterling1Per = sterling.value / 100;
var convert = sterling1Per * conversionRate.value;
var totalLessVat = convert + sterling.value;
//var total = (totalLessVat) + (vat.value * (totalLessVat / 100));
var euro1Per = totalLessVat / 100;
var addVat = euro1Per * vat.value;
var total = addVat + totalLessVat;
euro.value = Math.floor(total);
});
}
}
<div id="calculator-form">
<table>
<tr>
<td>Conversion Rate: </td>
<td><input type="number" id="conversionRate"> %</td>
</tr>
<tr>
<td>Sterling Price: </td>
<td><input type="number" id="sterling"> £</td>
</tr>
<tr>
<td>Vat: </td>
<td><input type="number" id="vat"> %</td>
</tr>
<tr>
<td>Euro Price is </td>
<td><input type="number" id="euro" disabled> €</td>
</tr>
</table>
</div>
The .value of an input is going to be a String, so you will need to parse the number out of each input you are working with. If it's an int you can use:
var sterling1Per = parseInt(sterling.value, 10) / 100;
If it's a float, you can use:
var sterling1Per = parseFloat(sterling.value) / 100;
Anywhere that you use an input .value that needs to be a number needs to be parsed accordingly

Categories

Resources