如何在Javascript方程中引用表单字段

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

本文关键字:引用 表单 字段 方程中 Javascript      更新时间:2023-09-26

我有这个JavaScript,它将一系列数字相加并创建一个总数。然后从这一系列数字中找出最小的一个,从总数中减去它。我希望用户能够输入一个数值,并有这个数字是方程的一部分。我先给你我的代码,然后再告诉你我做了什么。

这是执行加法和减法的脚本:

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;
}

这是我创建的表单字段,我想把它拉到等式中:

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

我认为通过添加:

var withDiscount = total + yellowtape - min ;

它会工作,但我不明白。我需要将他们在表单字段'yellowtape'中输入的任何数字添加到var withDiscount。

yellowtape为DOM元素。你需要取它的值,并确保它是一个数字:

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

如果您先存储输入值,您所拥有的将会工作:

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