选择onchange事件触发javascript拉取数组值并替换隐藏字段的值

时间:2012-02-01 19:34:43

标签: javascript html

在上一个问题之后我没有得到任何回复。感谢所有人,我从上一个问题得到了很多帮助。我这样做是基于选择“关注”它将从数组中提取镜像索引值(电子邮件地址)并用它替换“收件人”值。有一些选项可以提取相同的电子邮件地址。这是我遇到的最后一个问题 - 带有这个带有“电子邮件#1,电子邮件#2,......”的java脚本的测试页面在mtsherman的测试页面上工作(非常感谢!)。当我将实际的电子邮件添加到此数组中时,它不会将值拉到收件人值。这可能是一个非常简单的修复,但我是新手,难倒!提前谢谢。

<html>
<head>
<script language="JavaScript">
document.getElementById('Concerning').onchange = function() { 
    var myArray = ["Empty", 
                   "None@none.com", 
                   "None1@none.com", 
                   "None2@none.com", 
                   "None1@none.com", 
                   "None4@none.com", 
                   "None5@none.com", 
                   "None1@none.com", 
                   "None7@none.com", 
                   "None8@none.com",
           "None9@none.com",
           "None5@none.com",
           "None8@none.com"];

    document.getElementsByName('recipient')[0].value = myArray[this.selectedIndex];
};
</script>
</head>
<body>
<form action="/cgi-bin/formmail" method="post">
<select id="Concerning">
                    <option value="Choose One">Choose One
            <option value="Benefits">Benefits
            <option value="Customer_Service">Customer Service
            <option value="Employee_Paperwork">Employee Paperwork
            <option value="Human_Resources"> Human Resources
            <option value="Open_Positions">Open Positions
            <option value="Payroll">Payroll
            <option value="Quote_Request">Quote Request
            <option value="Safety">Safety
            <option value="Technical_Support">Technical Support
            <option value="Training">Training
            <option value="Unemployment">Unemployment
            <option value="Workers_Compensation">Workers' Compensation
    </select>
<input TYPE="hidden" NAME="recipient" VALUE="">
    <input TYPE="hidden" NAME="subject" VALUE="Contact Form">
    <input TYPE="hidden" NAME="email" VALUE="postmaster@company.com">
    <input TYPE="hidden" NAME="required" VALUE="Name,Phone,Email,Concerning,Comments">
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的代码在页面加载之前正在运行。您应该会在JavaScript控制台中看到错误,抱怨document.getElementById('Concerning')null。使用onload处理程序来延迟代码的执行,直到页面准备就绪:

window.onload = function () {
    document.getElementById('Concerning').onchange = function () {
        ...
    };
};