我正在编写一个小型数据库,在这里我可以扫描多个条形码到不同的文本框中,然后保存数据。条形码数据可以有一些变化长度,我想移动焦点到下一个文本框后,条形码完成扫描。
下面是我认为的最新代码,其中我给每个文本框一个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个字符输入/扫描到第一个文本框后,这应该会将焦点移到下一个文本框,但这不起作用。
然后,我想让焦点改变后,条形码的可变长度进行扫描,但不确定如何做。
我的代码做错了什么,不会让焦点改变到下一个文本框?
发布于 2015-07-21 04:30:08
我发现我遇到的主要问题是我在代码开始时忘记了包含$(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。
发布于 2015-07-16 05:31:43
更新:
您可以尝试以下几种方法:
$('input[id*="focus"]').each(function () {
if($(this).val().length >= 2) {
$(this).next().focus();
}
});
我不确定你的结构,但jQuery是非常直接的。使用单词focus
迭代每个元素,如果值大于2,则将焦点移到下一个元素。(可能需要调整到适当的元素)
而且,这将有一定的开销,因为每次迭代都会出现一个循环。
我不确定keyup
事件是否真的会被触发。另外,你要确保它等于2,不等于或更大。不过,您可以执行以下操作:
$('input[id=focus]).change(function (event) {
event.preventDefault();
if($(this).val().length >= 2) {
$('input[id=focus2]').focus();
}
});
您还可能希望扩展这段代码,在该代码中,它会自动递增到下一个可用的id
进行焦点处理。
https://stackoverflow.com/questions/31455277
复制相似问题