用于检查输入值的jquery不';行不通

用于检查输入值的jquery不';行不通,jquery,focus,Jquery,Focus,我使用jquery“checkcus(str)”来检查输入字段是否为空。如果我关注输入字段,而它是空的,那么输入的背景色应该变成红色。否则,它应该关注id为“nextInput”的下一个输入字段 这是我输入字段的代码 另外,我不需要输入和检查maxlength,因为输入是'name',所以应该没有字符限制 <div id='input1'> Name <input type = 'text' id = 'firstInput' onfocus='checkcus(this.i

我使用jquery“checkcus(str)”来检查输入字段是否为空。如果我关注输入字段,而它是空的,那么输入的背景色应该变成红色。否则,它应该关注id为“nextInput”的下一个输入字段

这是我输入字段的代码

另外,我不需要输入和检查maxlength,因为输入是'name',所以应该没有字符限制

<div id='input1'>
 Name <input type = 'text' id = 'firstInput' onfocus='checkcus(this.id)'>
  </div>
<div id = 'input2'>
 Code <input type = 'text' id = 'nextInput'>
</div> 

名称
密码

我不熟悉jquery,我认为我的代码中有一个问题,为什么它不工作。

如果输入元素为空,那么字段的值将是空字符串(
'
),您正在检查它是否是字符串值
'null'
,它与
null
值也不相同

function checkcus(str) {
    var el = document.getElementById(str);
    if (el.value === '') {
        el.style.backgroundColor = "red";
    } else {
        document.getElementById('nextInput').focus();
    }
}
演示:


因为您使用的是jQuery,所以请使用jQuery事件处理程序

Name<input type='text' id='firstInput'/>
Code<input type='text' id='nextInput'>

演示:

您只需检查输入的长度即可。我还对您的示例进行了jQuery验证,因为您使用jQuery标记了您的问题:

$('#firstInput')。焦点(函数(){
if($(this).val().length==0){
$(this.css('backgroundColor','red');
}否则{
$('#nextInput').focus();
}
})

名称
密码

给jQuery一个镜头

$(函数(){
$('#firstInput')。on('focusin',function(){
if(this.value.trim()=''){
$(this.css('background-color','#ff0000');
}否则{
$('#nextInput').focus();
}
})
.on('input',function(){
if(this.value.trim()!=“”){
$(this.css('background-color','#ffffff');
}
});
});

名称

Code
旁注,如果您使用的是jQuery,那么就使用jQuery。例如,代替
document.getElementById(str.style.backgroundColor=“red”
do
$('#'+str).css('backgroundColor','red')
谢谢,它能用。但我还有一个问题。我把这两个放在不同的标签上,它不起作用。为什么呢?像这样:Name Code@makarov你能编辑上面的小提琴来重现问题吗问题可能是你有重复的ID,元素的ID必须是唯一的…非常感谢!我知道现在有什么问题了。你说得对,我有两个相同的身份证,这就是为什么它对我不起作用。谢谢@Arun
Name<input type='text' id='firstInput'/>
Code<input type='text' id='nextInput'>
jQuery(function($){
    $('#firstInput').focus(function(){
        if(this.value===''){
            $(this).css('background-color', 'red');
        }else{
            $('#nextInput').focus();
        }
    })
})