【发布时间】:2014-10-17 12:14:00
【问题描述】:
对于我正在开发的网站,我使用表单来更新模型的不同字段。
其中一些字段需要根据其他字段的值进行更新。 例如,任务的每个实例都有一个开始日期、一个结束日期和一个长度,它们必须验证以下内容:结束 = 开始 + 长度(周末不计算在内,但这是次要问题)。
所以我正在尝试编写的功能之一是:
When the user changes the value of the input Start_date
Get that date from the input field
Get the value of the field Lenght
Update the value of the input "End date" with (Start_date + Lenght)
我的示例涉及的三个输入具有以下 ID:id_start、id_lenght、id_finish。
这是我写的,但根本不起作用(没有任何可见的事情发生......):
<script>
$( "#id_start" ).change(function() {
var start = new Date();
var finish = new Date();
var numberOfDays = document.getElementById('id_lenght').value;
start = document.getElementById('id_start').value;
finish.setdate(start.getDate()+document.getElementById('id_lenght'))
$('#id_finish').val(finish);
});
</script>
我们将不胜感激任何有关使其发挥作用的解决方案的提示。 提前致谢。
【问题讨论】:
-
Knockout.js 非常适合这项工作。您可以对元素进行数据绑定并定义它们之间的可计算关系。 knockoutjs.com 将它与 MomentJS 结合使用,您也可以轻松进行日期操作。 momentjs.com
-
如果
$("#id_start")是<input>使用keyup或blur事件。 -
@Burn 你的意思是更改事件不适用于输入元素吗?...
-
@OleBorgersen 对于我更广泛的问题,这似乎是一个很好的解决方案。我会看看它。谢谢。
-
@Emeric 确实如此,但它在
blur上触发。所以使用keyup:)Change事件更适合<select>。
标签: javascript forms javascript-events