如何在 jQuery 中为文本框提供焦点

how to give focus for text box in jquery?

本文关键字:焦点 文本 jQuery      更新时间:2023-09-26

当用户输入错误的值时,我想聚焦文本框,但我不知道如何在代码中添加focus()。 任何建议

<input type="text" class="form-control" id="txtfirstname" alt="spnfirstname" name="txtfirstname">
<input type="text" class="form-control" id="txtmiddlename" name="txtmiddlename" alt="spnmiddlename">
$('document').ready(function () {
    $('#txtfirstname,#txtmiddlename,#txtlastname,#txtmothertongue,#txtplaceofbirth')
            .bind('keyup', function () {
                var theValue = $(this).val();
                var spanid = $(this).attr("alt");
                if (theValue != '' && theValue.match(/^['a-zA-Z]+$/) == null)
                {
                    theValue = theValue.replace(/[^a-zA-Z, ]/g, '')
                    $("#" + spanid).text("alphabets only");
                    $('#txtfirstname').focus();
                }
                else
                    $("#" + spanid).text(" ");
            });
});
theValue = theValue.replace(/[^a-zA-Z, ]/g, '')
$("#" + spanid).text("alphabets only");
$(this).val(theValue);  <<== Add this
^^^^^^^^^^^^^^^^^^^^ 
$('#txtfirstname').focus();  //Remove this one

演示

监听 focusout 事件,检查输入是否无效,然后重新聚焦。

$('#txtfirstname').focusout(function(e) {
    if(invalidInput){
        $('#txtfirstname').focus();
    }
});

你不必放弃冻结。诀窍是防止键入事件的发生,这样值永远不会更改,除非您批准它。

我分叉了@Sadikhasan的小提琴:分叉演示

还有一件事,alt 属性具有语义值,应该在 img 标签中,您不应该像现在这样使用它。如果您仍想"引用"另一个元素,请考虑使用 data-* 属性。