vlookup-like javascript 将输入值从一个字段映射到另一个字段

vlookup-like javascript to map input value from one field to another

我刚刚开始 html/javascript,并尝试创建一个简单的表单,当从输入列表中选择 "Customer Name" 时填充特定的 "Customer Code"(表现得像 excel vlookup)。我在 Whosebug 上找到的示例都导致警报 windows,但我希望该值填充到表单中。

这是我的 html 客户名称下拉列表片段:

<select id="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>

这是客户名称到客户代码的映射: Doe Inc = 276。Smith LLC = 852。Rogers and Co = 552。

我希望每当更新客户名称时(不需要按钮),客户代码就会更新为相应的客户名称,因为这是一个更大的表单的一部分,将有一个提交按钮(换句话说,我不不希望用户必须单击 "Submit" 来检索客户代码,然后稍后在表单中再次单击 "Submit")。

谢谢!

希望这就是您要找的。 基本上,我使用一个数组来格式化您的数字,然后将 onchange 用于 select 元素并等待更改。当发生变化时,我触发一个事件,Javascript 获取字段的值,将它们与数组进行比较,并根据 selected 值 returns。

请参考 Tieson T. 回复,对静态有更多的解释和不同的方法 html!

var drop_down = document.getElementById("customername");
var result = document.getElementById("result");
var list_array = {
  "": "Please Select A Value",
  "Doe Inc": 276,
  "Smith LLC": 852,
  "Rogers and Co": 552
}

function change_value() {
  if (list_array[drop_down.value]) {
    result.innerHTML = list_array[drop_down.value];
  }
}
<select id="customername" onchange="change_value()">
  <option></option>
  <option>Doe Inc</option>
  <option>Smith LLC</option>
  <option>Rogers and Co</option>
</select>
  
<span id="result"></span>

为了包含在表单提交中,您的表单控件需要成功控制,最简单的意思是它们需要 name="" 值:

<select id="customername" name="customername">
    <option></option>
    <option>Doe Inc</option>
    <option> Smith LLC </option>
    <option> Rogers and Co </option>
</select>

如果您真正关心提交的是customercode,而customername只是"friendly"版本,请将value属性添加到您的选项中,并适当地重命名select :

<select id="customercode" name="customercode">
    <option value="">Select one...</option>
    <option value="276">Doe Inc</option>
    <option value="852">Smith LLC </option>
    <option value="552">Rogers and Co </option>
</select>

如果您希望 "values" 在表单上可见并包含在表单提交中,您可以使用 data- 属性来同步只读输入:

<select id="customername" name="customername">
    <option data-value="">Select one...</option>
    <option data-value="276">Doe Inc</option>
    <option data-value="852">Smith LLC </option>
    <option data-value="552">Rogers and Co </option>
</select>

<input type="text" name="customercode" id="customercode" readonly />

然后使用一些JavaScript来同步它们:

var select = document.getElementById('customername');
select.onchange = function(e) {
  var value = select.options[select.selectedIndex].dataset.value;

  var input = document.getElementById('customercode');
  input.value = value;
}

示例 jsFiddle:https://jsfiddle.net/27jx0q3a/3/

一些链接,帮助: