【问题标题】:Change Select option based on input field dynamically while typing键入时根据输入字段动态更改选择选项
【发布时间】:2019-03-03 07:12:26
【问题描述】:

我的项目中有一个输入字段和一个选择字段。我想根据用户输入的内容(字母和数字的组合)动态更改选择选项。用户也可以自己选择,动态变化是一种帮手。

<input id="userInput" type="text" class="form-control" placeholder="Type here">

<select id="sel" class="form-control form-control-xl">
  <option selected>Choose one</option>
  <option value="1">Dog</option>
  <option value="2">Cat</option>
  <option value="3">Lizard</option>
  <option value="4">Fish</option>
</select>

该选项基于这样的逻辑

var userInput = document.getElementById('userInput').value;
var sel = document.getElementById('sel');

if (userInput firstletter is Z and followed by numbers) {
    $('#sel').val('1').change(); // Dog
} else if (userInput beginsWith === AB and endsWith === YZ with numbers between) {
    $('#sel').val('2').change(); // Cat
} else if (userInput endsWith === XX) {
    $('#sel').val('3').change(); // Lizard
} else if (userInput beginsWith === 222) {
    $('#sel').val('4').change(); // Fish
}

将选项更改为类似于带有自动建议的搜索字段的正确方法是什么?

【问题讨论】:

  • 使用正则表达式.......
  • 输入的字母数字字符串与&lt;select&gt;中的选项有什么关系?
  • 字母数字字符串的类型由订单字符串决定选项,例如。 Z12345 id 代表狗,AB12345YZ 代表猫。
  • Select2 或 Selectize 会为你做的

标签: javascript dynamic drop-down-menu


【解决方案1】:

您可以为每个模式创建一个regex 作为dictionary。然后你可以在文本框值改变时循环匹配它。

var dict = []; // create an empty array

window.onload = function(){

dict.push({key:   "1",  value: "^z+[0-9]*$"}); //firstletter is Z and followed by numbers
dict.push({key:   "2",  value: "^AB.[0-9]*YZ$"}); //beginsWith === AB and endsWith === YZ with numbers between
dict.push({key:   "3",  value: "^Cat$"});
dict.push({key:   "4",  value: "^Lizard$"});
dict.push({key:   "5",  value: "^Fish$"});

}


function test()
{

var userInput = document.getElementById('userInput').value;
var sel= document.getElementById('sel');
sel.value = "";
var isMatched = false;

 for(var i = 0; i < dict.length; i++)
    {
        var reg = eval("/" + dict[i].value + "/gi");
        
        isMatched = reg.test(userInput);
        console.log(i + " " +userInput + " " + isMatched + " Key: " + dict[i].key);
        
        if (isMatched)
        {
          sel.value = dict[i].key;
          break;
        }   
      }
}
<input id="userInput" type="text" class="form-control" placeholder="Type here" onchange="test()" onchange="test()">

<select id="sel" class="form-control form-control-xl">
  <option value="" selected>Choose one</option>
  <option value="1">First Letter Z and then numbers</option>
  <option value="2">Begins with AB and number in between adn ends with YZ</option>
  <option value="3">Cat</option>
  <option value="4">Lizard</option>
  <option value="5">Fish</option>
</select>

【讨论】:

  • 这太棒了!一个问题 - 有时我必须采取行动来改变价值,例如。在输入字段之外单击。有没有办法解决这个问题?
  • 尝试其他活动onKeyUp 或orKeyDown
猜你喜欢
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
相关资源
最近更新 更多