我的项目中有一个输入字段和一个选择字段。我想根据用户输入的内容(字母和数字的组合)动态地更改选择选项。用户也可以自己选择它,动态变化有点像帮助程序。
<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
}
类似于自动建议的搜索字段,更改选项的正确方法是什么?
答案 0 :(得分: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>