繁体   English   中英

JavaScript使用HTML组合框填充输入字段

[英]JavaScript Populating an input Field Using an Html combo Box

我试图找到一种方法,允许用户单击组合框中的项目,并使其值填充输入字段,并在选择适当的选项时提醒“工作停止”或“工作开始”消息。 但是我的代码无法正常工作。 请帮忙! 这是我的代码:

    <html>
    <head>

    </head>
    <body>

    <form>
<select name="sel1" onChange="populateField(this.form)" >
    <option value="">---Select---</option>
    <option value="stop" >Stop</option>
    <option value="start">Start</option>
</select>

<input type="text" id="eStop" name="eStop" />
</form>
<script type="text/javascript">

function populateField(frm){
 test = frm.stop.value;
 alert('work' test);
 frm.eStop.value = test;
}
</script>
    </body>
    </html>

提前致谢

http://jsfiddle.net/snHQY/

<form>
    <select name="sel1" id="select" onchange="populateField();" >
        <option value="">---Select---</option>
        <option name="stop" value="stop" >Stop</option>
        <option name="start" value="start">Start</option>
    </select>

    <input type="text" id="eStop" name="eStop" />
</form>

<script>
function populateField() {
    test = document.getElementById('select').value;
    alert(test);
    document.getElementById('eStop').value = test;
}
</script>

您也可以使用selectedIndex进行操作,

<form>
    <select name="sel1" id="select" onchange="populateField(this);" >
        <option value="">---Select---</option>
        <option name="stop" value="stop" >Stop</option>
        <option name="start" value="start">Start</option>
    </select>

    <input type="text" id="eStop" name="eStop" />
</form>

<script>
function populateField(sel) {
  sel.form.eStop.value = 'work ' + (sel.selectedIndex == 1 ? 'Stop' : 'Start');
}
</script>

http://jsfiddle.net/cnpuM/

在你的选择,你可以添加到onchange's和onkeypress事件的populateField的功能, this为对象引用。

<select name="sel1" onchange="populateField(this)" onkeypress="populateField(this)">

现在,您可以引用o的选择。 将选定的值传递到警报对话框和输入字段。

function populateField(o){

  alert("work " + o.value);
  // use regular W3C DOM syntax for element referencing the input and populate it with the select objects selected options value
  document.getElementById("eStop").value = o.value;
} 

您的代码有两个错误。 您不能通过元素的值来引用它,例如test = frm.stop.value; 而是使用test = frm.sel1.value; 此行中的另一个错误是alert('work' test); 在这里,您将字符串“ work”与变量“ test”连接在一起。 在Java脚本中,无论何时连接两个或多个变量或字符串和变量,都必须始终用+符号将它们连接起来,如下所示: alert('work ' + test); 剩下的代码还可以:

<html>
<head>

</head>
<body>
<form>
<select name="sel1" onChange="populateField(this.form)" >
<option value="">---Select---</option>
<option value="stop" >Stop</option>
<option value="start">Start</option>
</select>

<input type="text" id="eStop" name="eStop" />
</form>
<script type="text/javascript">
function populateField(frm){
    var test = frm.sel1.value;
 alert('work '+ test);
frm.eStop.value = test;
}
</script>

</body>
</html>

您也可以使用“ sel1”的selectedIndex属性进行相同的操作。

暂无
暂无

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

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