当用户输入错误的值时,我想聚焦文本框。但是我不知道如何在我的代码中添加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
Demo