user2339898
user2339898

Reputation: 91

How do I reference a form field in a Javascript equation?

I have this JavaScript, which adds up a series of numbers and creates a total. Then from that series of numbers it finds the lowest one and subtracts it from the total. I want the user to be able to input a numeric value and have that number be part of the equation. First I'll give you my code and then I'll tell you what I've tried.

This is the script that does the addition and subtraction:

var prices = [];
function remove(arr,itm){
  var indx = arr.indexOf(itm);
  if (indx !== -1){
    arr.splice(indx,1);
  }
}

function calculateSectedDues(checkbox, amount) {
  if (checkbox.checked === true) {
    prices.push(amount);
  } else {
    remove(prices, amount);
  }
  var total = 0;
  for (var i = 0, len = prices.length; i < len; i++)
    total += prices[i];

  var min = prices.slice().sort(function(a,b){return a-b})[0];
  if(typeof min === 'undefined') min = 0;
  var withDiscount = total - min;
  var discountAmount = withDiscount - total;
  document.querySelector("#total").innerHTML = total;
  document.querySelector("#discount").innerHTML = discountAmount;
  document.querySelector("#newTotal").innerHTML = withDiscount;
  document.getElementById("FinalTotal").value = withDiscount;
}

This is the form field I created that I want to pull into the equation:

<input name="yellowtape" type="text" id="yellowtape" style="width:243px;">

I thought that by adding:

var withDiscount = total + yellowtape - min ;

It would work but I cant figure it out. I need to add whatever number they enter in the form field 'yellowtape' to var withDiscount.

Upvotes: 2

Views: 1627

Answers (2)

dda
dda

Reputation: 6213

yellowtape is the DOM element. You need to take its value and make sure it's a number:

var yellowtape = parseFloat(document.getElementById('yellowtape').value);
var withDiscount = total + yellowtape - min ;

Upvotes: 2

Sharlike
Sharlike

Reputation: 1789

What you have will work if you store the input value first:

var yellowtape = document.getElementById('yellowtape').value;
var withDiscount = total + yellowtape - min ;

Upvotes: 0

Related Questions