将一个组合框值传递给其他组合框

Passing a combobox value to the other combobox

本文关键字:组合 值传 其他 一个      更新时间:2023-09-26

我有两个组合框:

<select ID="combobox1"></select>
<select ID="combobox2" onChange="get_function(this, #combobox1)"></select>

我想做的是,将combobox1上选择的值传递给combobox2,并调用Javascript函数:

function get_function(combobox1, combobox2)
{
var code1 = combobox1.value;
var code2 = combobox2.value;
if (!code1) return;
if (!code2) return;
alert(code1 + '-' + code2);
}

我试过那个代码,但它不起作用。我该怎么做?


更新

问题解决者:

<select ID="combobox1"></select>
<select ID="combobox2" onChange="get_function(this, "combobox1")"></select>
function get_function(combobox1, combobox2)
{
var code1 = combobox1.value;
var code2 = document.getElementById(combobox2);
if (!code1) return;
if (!code2) return;
alert(code1 + '-' + code2);
}

演示:

function get_function(el, to_el_id) {
  var to_el = document.getElementById(to_el_id);
    if (to_el) {
        to_el.value = el.value;
    }
}​

我建议(如果必须使用内联JavaScript):

function get_function(combobox1, combobox2) {
    var code1 = document.getElementById(combobox1).value,
        code2 = combobox2.value;
    if (!code1 || !code2) {
        return false;
    }
    else {
        alert(code1 + '-' + code2);
    }
}

这样调用这个函数:

<select id="combobox1"></select>
<select id="combobox2" onchange="get_function('combobox1', this)"></select>

JS Fiddle演示。

在最初的HTML中,您调用函数时使用了错误顺序的参数,并且第二个参数(即第一个元素的id)使用了未加引号的字符串。此外,据我所知,您并没有试图使用id来获得对相关DOM节点(元素本身)的引用,您只是直接使用id(一个未加引号的字符串,因此被解释为不存在的全局变量)。这永远不会奏效。

<select ID="combobox1"></select>
<select ID="combobox2" onChange="get_function(this, "combobox1")"></select>
function get_function(combobox1, combobox2)
{
  var code1 = combobox1.value;
  var code2 = document.getElementById(combobox2);
  if (!code1) return;
  if (!code2) return;
  alert(code1 + '-' + code2);
}