How to subtract values from text field to apply discount from total? - javascript

Here is my code
What i am trying to do is to subtract from total value to give discount.
<script type="text/javascript">
function gettotal(){
var arr = document.getElementsByName('feetype');
var discount = parseInt(document.getElementsByName('discount').value);
var tot=0;
for(var i=0;i<arr.length;i++){
if( parseFloat(arr[i].value))
tot += parseFloat(arr[i].value);
tot = tot - discount;
}
document.getElementById('recieveable').value = tot;
}
</script>
enter image description here

Well this is wrong var discount = parseInt(document.getElementsByName('discount').value);
document.getElementsByName returns array of element but here you are expecting a single element. Therefore you should user document.getElementById instead OR you can use what you are using with array index.
Change it to
var discount = parseInt(document.getElementById('discount').value);
OR
var discount = parseInt(document.getElementsByName('discount')[0].value);
if you've only one discount field.

Related

free shipping ... if shopping chart total is greater than $35 ... user input unless total is more $35 in JavaScript

I m not sure what i m doing wrong. Thanks in advance for helping me in this matter.
var sum = 0;
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
Declare sum to zero each time you are executing the sum of items. Or else it will keep on adding to the sum that was calculated in previous iteration.
Also your submitprice seems to be undefined. I have initilaized it as an empty array.
Working Fiddle
var sum = 0;
var pricecheck = 35;
const submitprice = [];
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
sum = 0;
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
To start, you need to create an empty array to store the totals in. For this, I will call it "cart":
var cart = [];
Next, I would suggest creating an if statement to check if the input is a number:
var num1 = parseInt(userinput);
if(isNaN(userinput){
alert("Please enter a number");
continue;
}
You don't need the for loop to add the input to the sum, just remove the loop:
sum += userinput
After the loop, you would push to the cart:
cart.push(num1)
Finally, you need to check if the sum is more than free shipping
if(sum >= pricecheck) {
alert("You qualify for free shipping!")'
}
Then just output the result to the console with a pipe (|) concatenated between the numbers.
console.log(cart.join(" | ")
var sum = 0;
var cart = [];
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
if (userinput === null) {
break;
}
var num1 = parseInt(userinput);
if (isNaN(userinput)) {
alert("Please enter a number");
continue;
}
cart.push(num1);
sum += num1;
}
if (sum >= pricecheck) {
alert("free shipping.");
}
I took a look at this assignment again to refresh on what was asked for this question. You do not need to have that for loop at all within the while loop. Within each iteration of the while loop, you are asking the user for the price of their next item, adding it to the shopping cart, and also adding it to a running total (this total being your "sum"). This running total does not need to be re-calculated each time inside of the while loop because you would have done that in a single line. You are trying to calculate the price, starting at 0, each time you loop through the while loop (using your for loop). But this is not needed as you already have a running total that can be added to each time the user enters a value.
"Austin Caron" explained it well but for this assignment we do not need to do user authentication.
P.S. Try your best to avoid asking questions directly about an assignment and ask more general questions about a concept or idea you are struggling with.

Nan proplem in JS

I have some problem with my js code which when I run the code it show me a NaN error, I have a function that calculate something.
Example:
<p id = "total "></p>
total = num1 *num2;
document.getElementById("total").innerHTML = total;
And it works fine but when I create a new function to calculate the discount
var price = document.getElementById("total").value;
discount = total *0.10;
It shows a NaN, I tried a lot of solution but it is still not working.
Can you help me?
I think you have a concept mistake, if the value is a HTML value, i mean, is inside of
<p id="this_is_the_element">123456789</p>
You can get that value with javascript using the
var number = document.getElementById('this_is_the_element').innerHTML
now the number variable will have inside "123456789" as a STRING
But if you are using an input you should use
var number = document.getElementById('this_is_the_element').value
Now, try this. First try to avoid the parseInt, instead use Number.
Define a function
var discount = function(){
var price = Number(document.getElementById("total").innerHTML);
return price*0.1;
}
If you want to do it on new sintax use this
const discount = () => {
const price = Number(document.getElementById("total").value);
return price*0.1;
}
There are few issues in your code:
There is no value property of p element. To access the text in p element, you can use either textContent or innerText.
By default the text is of type string. Multiplying string with number gives you NaN. You have to convert that to number before doing any arithmetic operation.
var num1 = 5;
var num2 = 20;
var total = num1 *num2;
document.getElementById("total").textContent = total;
var elTotal = Number(document.getElementById("total").textContent);
var discount = elTotal * 0.10;
console.log(discount)
<p id = "total"></p>
When you pull the value, it's a String, and JavaScript for the most part will automatically do type conversion, but you can always wrap it in parseInt to force it to be a Number.
discount = parseInt(total) * 0.10;
You can also always run typeof total to verify if total is a Number or String, and you can run console.log(total) to visually verify the contents.
Also, your document.getElementById("total") references a paragraph element, which doesn't have .value property, so you should use innerText to get its value instead.
Demo
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function() {
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
total = parseInt(num1) * parseInt(num2);
document.getElementById("total").innerText = total;
});
button2.addEventListener('click', function() {
var total = document.getElementById("total").innerText;
discount = parseInt(total) * 0.10;
document.getElementById('discount').innerText = discount;
});
<input type="text" id="num1" /><br>
<input type="text" id="num2" /><br>
<button id="button1">Add</button>
<p id="total"></p>
<button id="button2">Discount</button>
<p id="discount"></p>
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Javascript: Multiplying an input value with multiple table cell values and assign it to other table cells

I am trying to multiply an input value with multiple table cells and assign the results of each calculation to the table cell to the right of each cell except for the first row.
Here is my javascipt:
<script>
function updateTable() {
var x;
var itemPrice = document.getElementById("inputPrice");
var newPrice;
for (i = 1; i < 50; i++) {
x = document.getElementById("table1").rows[i].cells;
newPrice = (parseInt(x[1].innerHTML)+1) * itemPrice;
x[2].innerHTML = newPrice;
}
}
</script>
You forgot to get the value from inputPrice.
var itemPrice = document.getElementById("inputPrice").value;
You can see an example here

Jquery Converting a string to Integer

I am getting value using jquery text() mehtod. I want to calculate the SUM of this value with some other value that is a number. I am getting a NaN retun now. code is something like this
I have the value in my page like this <p id="typeinfo2">445</p>, value coming dynamically
var oldtotal = parseInt($('#typeInfo2').text(), 10);
var xtra = 75;
var newtotal = oldtotal + xtra;
alert(newtotal) gives me a NaN. I have already tried with - Number(oldtotal) + Number(xtra)
You have a typo. id of p tag is typeinfo2 and not typeInfo2:
var oldtotal = parseInt($('#typeinfo2').text(), 10);
Working Demo
Your spelling mistake
Change Id typeInfo2 to typeinfo2 in your jQuery code.
var oldtotal = parseInt($('#typeinfo2').text(), 10);
var oldtotal = parseInt($('#typeinfo2').text(), 10);
var xtra = 75;
var newtotal = oldtotal + xtra;
alert(newtotal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id="typeinfo2">445</p>

How to get the textbox value when dropdown box value changed in javascript

I am having the
table which contains the table like
items  price  quantity  total
apple    100     2         200
orange  200    2           600
grand total=600.
item fields are dropdown when drop down changes the price will be changed and total value and grandtotal also changed. My problem is when selecting apple and orange again go to apple change the item my grand total is not changing.
My Javascript code:
function totalprice(element, price) {
var elementid = element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:" + expr).value;
var price = document.getElementById("price:" + expr).value;
if (quantity > 0) {
document.getElementById("total:" + expr).value = (parseInt(quantity)) * (parseInt(price));
var grandtotal = document.getElementById("total:" + expr).value;
var gtot = 0;
var amount = 0;
for (var i = 0; i <= expr; i++) {
//document.getElementById("total").value="";
gtot = document.getElementById("total:" + expr).value;
amount = parseInt(gtot) + parseInt(amount);
}
document.getElementById("total").value = amount;
}
return true;
}
I know the mistake is in for loop only it is simple one but i dont know how to solve.
I got the solution for this using table rows length and use that length to my for loop now my code is like
function totalprice(element,price)
{
var elementid=element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:"+expr).value;
var price = document.getElementById("price:" + expr).value;
if(quantity >0)
{
document.getElementById("total:"+ expr ).value= (parseInt(quantity))*(parseInt(price));
//var grandtotal =document.getElementById("total:"+expr).value;
//var grandtotal = document.getElementsByClassName("total"+expr);
var rowcount = document.getElementById('table').rows.length;
var grandtotal = 0;
var finalamount = 0;
for(var i=1; i<rowcount; i++)
{
grandtotal=document.getElementById("total:"+i).value;
finalamount = parseInt(grandtotal) + parseInt(finalamount);
}
document.getElementById("total").value=finalamount;
}
return true;
}
Here is code what you need:
Java Script:
<script>
function getVal(e){
// for text
alert(e.options[e.selectedIndex].innerHTML);
// for value
alert(e.options[e.selectedIndex].value);
}
</script>
HTML:
<select name="sel" id="sel" onchange='getVal(this);'>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Cat</option>
</select>
I see two errors in your for loop, first you forgot to use i in your getElement so you're only going through the same field multiple times, second, you're only looping through the inputs previous to the field that was updated (i<=expr), when you actually want to go through all the "total" fields to get the grand total, I would suggest giving a class to all your total fields and then use this code for your loop
var total_fields = document.getElementsByClassName('total');
for (var i = 0; i < total_fields.length; i++) {
gtot = total_fields[i].value;
amount+= parseInt(gtot);
}
document.getElementById("total").value = amount;
I think the problem relies here:
"My problem is when selecting apple and orange again"
Because I don't see in your code that you are actually updating the elements id when you calculate the total.
So... If you do:
gtot = document.getElementById("total:" + expr).value;
First time will work, because expr var is the original one, then, gtot is the right element id
but...
...when you do a second change, that var has a different value now... and gtot will not match your element id to recalculate the new value. (or in worst case, will match another and update the wrong one)

Categories