简体   繁体   English

使用一种JavaScript函数在一种形式上进行多个输入

[英]Using one javascript function for multiple inputs on one form

We have a simple age calculating script, that takes a date input (3 selects - day, month, year) and determine how old. 我们有一个简单的年龄计算脚本,该脚本接受日期输入(3个选项-日,月,年)并确定年龄。 It is triggered by an onChange assigned to the year select. 它由分配给年份选择的onChange触发。

There are several date inputs scattered through the form, each one set up the same, other than the input names (day1 vs day 1 vs day 3, etc). 除了输入名称(第1天与第1天与第3天,依此类推)外,表格中分散了多个日期输入,每个日期输入都设置相同。

Currently we have simply duplicated the js code and manually changed the input variables ... 目前,我们只是复制了js代码并手动更改了输入变量...

function Age1()
{
var oldDay = document.step1.day1.value;
var oldMonth = document.step1.month1.value;
var oldYear = document.step1.year1.value;
and more script....

function Age2()
{
var oldDay = document.step1.day2.value;
var oldMonth = document.step1.month2.value;
var oldYear = document.step1.year2.value;
and more script....

and so forth. 等等。

Ideally we would like to reuse one script, rather than hardcoding one for each instance. 理想情况下,我们希望重用一个脚本,而不是为每个实例进行硬编码。 I have tried a bunch of ideas to no avail, but the ideal would be to trigger it via: onChange="Age(X);" 我尝试了很多想法都没有用,但是理想的方法是通过以下方式触发它: onChange="Age(X);" and then have the js insert the proper variable: 然后让js插入适当的变量:

function Age(varX)
{
var oldDay = document.step1.dayX.value;
var oldMonth = document.step1.monthX.value;
var oldYear = document.step1.yearX.value;
and so on ....

Any ideas for us ? 对我们有什么想法吗? Thanks in advance 提前致谢

function Age(varX)
{
    var oldDay = document.step1['day' + varX].value;
    var oldMonth = document.step1['month' + varX].value;
    var oldYear = document.step1['year' + varX].value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM