简体   繁体   English

更改下拉列表中的关键搜索行为(选择字段)

[英]change key search behaviour on dropdown (select field)

I have a dropdown which shows a list of products formatted as "code - description" as shown bellow. 我有一个下拉列表,其中显示了格式为“代码-说明”的产品列表,如下所示。 Is it possible to search the selection for description instead of code? 是否可以在选择内容中搜索描述而不是代码? When the user click the "B" key for example the desired behaviour would be to select the 4th option. 例如,当用户单击“ B”键时,所需的行为将是选择第四个选项。

<option value="34">0050001 - ACUCAR 1KG UNIÃO</option>
<option value="1014">0370024 - AGUA DESTILADA PARA BATERIA 1 LT</option>
<option value="284">0040001 - ALCOOL GEL MULTI USO 500GR MILLE</option>
<option value="459">0010001 - BALDE PLASTICO 10L</option>
<option value="460">0010002 - BALDE PLASTICO 20L</option>
<option value="486">0020004 - BALDE PLÁSTICO COM ESPREMEDOR PULIRE</option>
<option value="285">0040002 - BASE SELADORA PROFIX MAX 2GL 5L ECOLAB</option>
<option value="491">0020009 - CABO ALUMINIO 1,40MTS C MANOPLA PARA MOP AGUA</option>
<option value="492">0020010 - CABO ALUMINIO 1,40MTS C MANOPLA UNIVERSAL CINZA</option>
etc

Without using a plugin this can be tricky. 如果不使用插件,这可能会很棘手。 I ended up using jQuery, a timeout fired on keyup and reset on keydown. 我最终使用了jQuery,在keyup上触发了超时,在keydown上重置了超时。

The logic is that the timeout handle the writing process, when stopped, using jQuery, search for the first option element that starts with the chars wrote and set it as selected. 逻辑是,超时在停止时使用jQuery处理写过程,并使用jQuery搜索以所写字符开头的第一个选项元素,并将其设置为选定状态。

Code: 码:

//setup before functions
var typingTimer;               //timer identifier
var doneTypingInterval = 500;  //time in ms, 5 second for example
var keyText='';

//on keyup, start the countdown
$('#SomeDropdown').keyup(function(e){
    clearTimeout(typingTimer);
    keyText+=String.fromCharCode(e.which);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#SomeDropdown').keydown(function(e){
    clearTimeout(typingTimer);    
});

//user is "finished typing," do something
function doneTyping () {

    $("#SomeDropdown option").filter(function() {
        return this.text.replace(/^[^-]*-/, '').trim().toUpperCase().indexOf(keyText, 0) === 0; 
    }).attr('selected', true);

    keyText='';
}

Demo: http://jsfiddle.net/v5vq7jL6/ 演示: http//jsfiddle.net/v5vq7jL6/

Known issues: 已知的问题:

  • back space open the select option and break the logic 退格键打开选择选项并破坏逻辑
  • when opened the select, custom typing is not recognized, it use the built in one 打开选择时,无法识别自定义键入,它使用内置的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM