【发布时间】:2018-11-21 01:19:40
【问题描述】:
我刚开始编程,所以答案可能很明显。我的代码有一个单选按钮(服务价格)和一个下拉菜单(订单数量),我想用这些值进行计算。到目前为止一切顺利,我花了将近一天的时间才得到这个简短的代码。
我现在的问题是,我需要实时显示结果,可能在像
这样的输入标签中 <p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" /></p>
也许还有更好的方法? 因此,应始终选中两个单选按钮之一并显示其价格。当用户从下拉菜单中选择数量时,结果应该会自动刷新。 谁能帮我?
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>ABC
<input class="test" type="radio" checked="checked" name="test" value="500">
</label>
<label>DEF
<input class="test" type="radio" name="test" value="800">
</label>
<select size="1" name="dropdown" onchange='calculate(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" /></p>
</body>
感谢您的帮助!
edit:好的,即使计算是错误的。我想获取选中的单选按钮的值并将其转换为 int。在此之后,我需要将 int 与复选框中的值相乘。我不知道我错过了什么,但它总是用第一个单选按钮值计算,即使我检查第二个。
<script>
var x = $('input[name="test"]:checked').val();
var xInt = parseInt(x, 10);
function calculate (val) {
var result = val * xInt ;
var amountPrint = document.getElementById('amount');
amountPrint.value = result;
}
$(".test").click(function(event) {
var total = 0;
$(".test:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#amount').val('');
} else {
$('#amount').val(total);
}
});
</script>
我仍然遇到问题,我需要实时显示结果,具体取决于选中的单选按钮和下拉值。所以我在单选按钮中添加了一个类“测试”并添加了上述功能。现在我得到了实时的结果,这取决于选中的单选按钮,但计算仍然是错误的,我需要以某种方式组合它。
【问题讨论】:
标签: javascript jquery html radio-button