扫描数据到mvc web应用程序,然后改变焦点

Scanning data into mvc web application then changing focus

本文关键字:然后 改变 焦点 应用程序 web 数据 mvc 扫描      更新时间:2023-09-26

我正在编写一个小数据库,在那里我可以扫描多个条形码到不同的文本框,然后保存数据。条形码数据可以在长度上有一些差异,我想在条形码完成扫描后将焦点移动到下一个文本框。

这是我视图中最新的代码,我给每个文本框一个id,然后我使用jquery在第一个文本框达到一定长度后关注下一个id。

<!--This is for entering the PartNumber-->
<div class="form-group">
    @Html.LabelFor(model => model.PartNum, 
       htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.TextBoxFor(model => model.PartNum, 
       new { htmlAttributes = new { @class = "form-control", id="focus1"} })
    @Html.ValidationMessageFor(model => model.PartNum, "", 
       new { @class = "text-danger" })
</div>
        <!--This is for entering the Aisle-->
        <div class="form-group">
            @Html.LabelFor(model => model.Aisle, 
               htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.TextBoxFor(model => model.Aisle, 
                new { htmlAttributes = new { @class = "form-control",id="focus2" } })
            @Html.ValidationMessageFor(model => model.Aisle, "", new { @class = "text-danger" })
        </div>
这是我的jquery代码
$('input[id=focus').keyup(function () {
        if (this.value.length == 2) {
            $('input[id=focus2]').focus();
        }
    });

从我从代码中可以看出,这应该在第一个文本框输入/扫描2个字符后将焦点移动到下一个文本框,但这不起作用。

我想在扫描可变长度的条形码后改变焦点,但不确定如何做到这一点。

我在代码中做错了什么,不会让焦点更改到下一个文本框?

更新:

您可以尝试以下操作:

$('input[id*="focus"]').each(function () {
     if($(this).val().length >= 2) {
          $(this).next().focus();
     }
});

我不确定你的结构,但jQuery是相当直接的。遍历包含单词focus的每个元素,如果值大于2,则将焦点移动到下一个元素。(可能需要调整next以击中合适的元素)

这也会有一些开销,因为每次迭代都会发生一个循环。


我不确定keyup事件是否会被触发。同时,你要确保它等于2,而不是等于或大于2。您可以这样做:

$('input[id=focus]).change(function (event) {
     event.preventDefault();
     if($(this).val().length >= 2) {
          $('input[id=focus2]').focus();
     }
});

您可能还想缩放此代码,其中它会自动增加到下一个可用的id焦点

我发现我遇到的主要问题是我忘记包含$(function(){在我代码的开头。接下来是我能想出的主要解决方案。

$(function(){
    $('#focus1').keyup(function(){
        if(!_timeoutRunning){
            _timeoutRunning=true;
            setTimeout(function(){checkKey();}, 2000);
        }
    });
});
var _timeoutRunning = false;
function checkKey(){
    _timeoutRunning = false;
    if($('#focus1').val().length >= 7)
        $('#focus2').focus();
}

这个代码允许我扫描长度为7或更多的条形码,然后在扫描第7个字符后2秒它会将焦点更改为下一个id