从输入字段更新javascript变量中的值

时间:2015-04-02 18:15:08

标签: javascript html

我有以下Javascript和HTML表单代码:

问题是,当我在字段中输入数值并按下提交按钮时,它不会将值发送到数量变量。如果我只是在输入值后刷新页面,那么它可以工作。如何通过单击“提交”按钮获取数量变量的值?

var button = document.getElementById("theButton")
var send = button.form.valueId.value;
var quantiy = send;
var costPerItem = 10;
var amount = costPerItem * quantiy;
var tax = (amount * 3) / 100;
var discount = (amount * 2) / 100;
var total = amount - discount + tax;

document.write('Tax', " " + tax + "<br>");
document.write('Discount', " " + discount + "<br>");
document.write('total', " " + total);
<form>
  <input type="text" id="formValueId" name="valueId" />
  <input value="submit" type="button" id="theButton" />
</form>

2 个答案:

答案 0 :(得分:0)

document.write用于将一些文本直接写入HTML文档。它以后不可编辑。所以你必须使用div并更新内部html

&#13;
&#13;
function updateVal() {
var button = document.getElementById("theButton")
var send= button.form.valueId.value ;
var quantiy=send;
var costPerItem=10;
var amount= costPerItem*quantiy;
var tax= (amount*3)/100;
var discount=(amount*2)/100;
var total= amount-discount+tax;

document.getElementById("tax").innerHTML = "Tax " + tax;
document.getElementById("discount").innerHTML = "Discount " + discount;
document.getElementById("total").innerHTML = "Total " + total;
  
  }

updateVal();
&#13;
<form>
<input type="text" id="formValueId" name="valueId"/>
<input  value="submit" type="button" onclick="updateVal()" id="theButton"/>
</form>

<div id="tax">Tax: 0</div>
<div id="discount">Discount: 0</div>
<div id="total">total: 0</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您为表单指定了名称并将按钮(input[type="button"])更改为提交按钮(input[type="submit"]),则可以收听onSubmit事件。

此外,通过将文本包装在跨度中,您可以控制输出的宽度和间距。

&#13;
&#13;
document.forms["myForm"].onsubmit = function() {
  var quantity = this.valueId.value;
  var costPerItem = 10;
  var amount = costPerItem * quantity;
  var tax = (amount * 3) / 100;
  var discount = (amount * 2) / 100;
  var total = amount - discount + tax;

  var output = document.getElementById('output');

  write(output, ''); // Clear previous text.
  writeValue(output, 'Tax', tax);
  writeValue(output, 'Discount', discount);
  writeValue(output, 'Total', total);
}

function writeValue(el, label, amount) {
  writeLine(el, el.innerHTML,
    '<span class="lbl">' + label + ':</span>',
    '<span class="val">' + amount.toFixed(2) + '</span>');
}

function write(el, value) {
  el.innerHTML = [].slice.call(arguments, 1).join(' ');
}

function writeLine(el, value) {
  write.apply(undefined, [].slice.call(arguments).concat('<br />'));
}
&#13;
span.lbl {
  display: inline-block;
  width: 80px;
  font-weight: bold;
}
span.lbl:after {
  content: '$';
  position: absolute;
  left: 84px;
}
span.val {
  display: inline-block;
  width: 56px;
  text-align: right;
}
div#output {
  margin-top: 1em;
}
&#13;
<form name="myForm">
  <input type="text" id="formValueId" name="valueId" value="42" />
  <input type="submit" id="theButton" value="submit" />
</form>

<div id="output"></div>
&#13;
&#13;
&#13;