当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - $(this).focus() not working when textbox is empty

问题描述:

My following code is not setting focus on textbox when it is when it is empty:

var empty = false;

$('.Newtxt').each(function () {

if ($.trim($(this).val()) == "") {

$(this).focus();

empty = true;

}

});

if (empty) {

return false;

}

Can we set focus on $(this) element? I have multiple textbox which needs to be validated with .Newtxt class.

网友答案:

Try this!

$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).focus();
        return false; // To break out of each loop
    }
});

ENjoy!!

网友答案:

Use:

var empty = false;

$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).focus();
        empty = true;
        break; // add this, you have to break cycle, to focus on the first found empty element...
    }
});

if (empty) {
    return false;
}
网友答案:

Finally I found one solution. Try that and let me know

$('.Newtxt').removeClass('invalid');
$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).addClass('invalid');
        empty = true;
    }
});

if (empty) {
    $(".invalid").eq(0).focus();
    return false;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: