我有以下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>
答案 0 :(得分:0)
document.write用于将一些文本直接写入HTML文档。它以后不可编辑。所以你必须使用div并更新内部html
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;
答案 1 :(得分:0)
如果您为表单指定了名称并将按钮(input[type="button"]
)更改为提交按钮(input[type="submit"]
),则可以收听onSubmit
事件。
此外,通过将文本包装在跨度中,您可以控制输出的宽度和间距。
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;