jQuery替换select中的值,具体取决于其他选择框 [英] jQuery Replace value in select depending on other select box

查看:107
本文介绍了jQuery替换select中的值,具体取决于其他选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

var LWTable = [];
LWTable.push([6,200,200,220]);
LWTable.push([8,220,220,240]);
LWTable.push([10,240,240,260]);
LWTable.push([12,260,260,290]);
LWTable.push([15,290,310,340]);
LWTable.push([18,330,360,400]);
LWTable.push([21,385,420,460]);

以及以下html:

<select name="plength" id="plength">
  <option value="6" selected>6 in.</option>
  <option value="8">8 in.</option>
  <option value="10">10 in.</option>
  <option value="12">12 in.</option>
  <option value="15">15 in.</option>
  <option value="18">18 in.</option>
  <option value="21">21 in.</option>
</select>
<select name="pwidth" id="pwidth">
  <option value="Width1" selected>Width 1 (xw1x)</option>
  <option value="Width2">Width 2 (xw2x)</option>
  <option value="Width3">Width 3 (xw3x)</option>
</select>

我想要的是,当我为plength选择值8时,在pwidth选择框中,将xw1x,xw2x和xw3x字符串替换为MinLoadTable中的值,因此在此示例中它将显示220, 220和240. 当我选择21时,它将自动用385,420,460替换该文本.

What I want is, that when I select value 8 for plength, that in the pwidth select box, the xw1x, xw2x and xw3x strings are replaced by the values from the MinLoadTable, so that in this example it would show 220, 220 and 240. When I pick 21, it will automatically replace that text with 385,420,460.

这有可能吗?我尝试查找一些示例,但没有得到任何结果... 任何帮助或指示,将不胜感激!

Is this possible and if so how? I tried to look up some examples, but didn't get anywhere... Any help or direction would be appreciated!

推荐答案

如果有可能将JS代码中的数据结构更改为对象,则可以进行非常详细的说明.首先,您可以从对象的键上创建plength选择选项.然后,在更改plength时,可以使用选定的值在对象中找到键,并填充pwidth的选项.试试这个:

If its possible to change the data structure in the JS code to an object you can make this very striaghtforward. Firstly you can create the plength select options on load from the keys of the object. Then on change of plength you can use the selected value to find the key in the object and populate the options of pwidth. Try this:

var LWTable = {
  '6': [200, 200, 220],
  '8': [220, 220, 240],
  '10': [240, 240, 260],
  '12': [260, 260, 290],
  '15': [290, 310, 340],
  '18': [330, 360, 400],
  '21': [385, 420, 460],
}

var plengthOptions = '';
Object.keys(LWTable).forEach(function(key) {
  plengthOptions += '<option value="' + key + '">' + key + ' in.</option>';
});

$('#plength').append(plengthOptions).change(function() {
  var pwidthOptions = '';
  LWTable[this.value].forEach(function(width, i) {
    pwidthOptions += '<option value="Width' + (i + 1) + '">Width' + (i + 1) + ' (' + width + ')</option>';
  });
  $('#pwidth').html(pwidthOptions);
}).change();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="plength" id="plength"></select>
<select name="pwidth" id="pwidth"></select>

这篇关于jQuery替换select中的值,具体取决于其他选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆