[英]Dynamically Update fields through Input field and dropdown
I'm trying to dynamically update a text field through an input field. 我正在尝试通过输入字段动态更新文本字段。 This will then be linked to a dropdown selection with values.
然后,这将链接到带有值的下拉列表选择。 I also need to show a due date to show 30 days in advance from today's date.
我还需要显示从今天开始提前30天显示的截止日期。
Here is my HTML: 这是我的HTML:
<div>
<label for="payment">Payment:</label>
<input type="text" name="amount" id="amount" onChange="myfunction()"/>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1">Fast</option>
<option value="2">Medium</option>
<option value="3">Slow</option>
</select>
</div>
<br />
<div>
Payment Breakdown: <br /><br />
Payment:
<div name="amount" id="amount"></div>
Freight:
<div name="delivery" id="delivery"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
</div>
I'm struggling with the Javascript part though and fitting it all together. 我正在努力使用Javascript部分并将它们整合在一起。
I've gotten as far as this and now I'm stuck. 我已经达到了这一点,现在我被卡住了。 (Not very far I know)
(我知道的不是很远)
function myFunction()
{
var amount = document.getElementById("amount");
var delivery = parseInt($(this).find("option:selected").val());
total = amount + delivery
$("#total").html(total);
};
I've looked at examples on Stackoverflow and Google but nothing seems similar to what I'm trying to achieve. 我查看了Stackoverflow和Google上的示例,但似乎没有什么与我想要实现的相似。 Although I know the answer is out there, I'm not sure if I'm asking the right question.
虽然我知道答案就在那里,但我不确定我是否在问正确的问题。
Cheers 干杯
I would change it to this. 我会改变它。 Here I have an
updateCost()
function which is called when the amount is changed or the delivery is changed. 这里我有一个
updateCost()
函数,当更改金额或更改交付时调用该函数。 I also added code to handle the due date. 我还添加了代码来处理截止日期。
Remove the inline onchange
event from the amount: 从金额中删除内联
onchange
事件:
<input type="text" name="amount" id="amount"/>
Javascript: 使用Javascript:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = amount + delivery
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
// handle the due date
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30);
var dateStr = todayPlus30.getDate() + "/" + (todayPlus30.getMonth()+1) + "/" + todayPlus30.getFullYear();
$('#date').html(dateStr);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
Your original code has a few problems: 您的原始代码有一些问题:
this
within the function when this
is not actually any of your elements (you didn't pass it as an argument). this
当函数内this
其实不是您的任何元素(你没有把它作为一个参数)。 amount
in the calculation when amount
is an input element, not a value. amount
在计算时amount
是输入元件,而不是一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.