2013-02-24 44 views
0

我显示了注册表单的错误消息/警报,它指向具有错误的输入。表单验证 - 专注于“错误”输入

我也想关注这个错误输入。

但是,我的代码目前主要集中在最后一次输入?

继承人链接。重新创建,只需点击寄存器而不填写任何内容。错误显示为第一个div ...但着重于最后一个。

link

我当前的代码:

$('#register-btn').on('click', checkEmpty); 

function checkEmpty(){ 
    var emptyDiv = $('.add-listing-input').filter(function() { 
     return $(this).val() == ""; 
    }); 

    if(emptyDiv.length > 0){ 
     var theTop = emptyDiv.position(); 
     var theBottom = theTop.top + emptyDiv.height() +25; 
     var theText = emptyDiv.attr('id'); 
     $('#register-errors').css('top',theBottom+'px').show(); 
     $('#error-text').text('Your '+theText+' is missing, please fill in'); 
     emptyDiv.focus(); 
     emptyDiv.on('keydown', function(){ 
       $('#register-errors').hide(); 
       $('#error-text').text(''); 

     }); 
    }else{ 
     $('#register-errors').hide(); 
     $('#error-text').text(''); 
     checkEmails() 
    } 

} 

回答

2

由于emptyDiv实际上是所有空字段的集合,说像emptyDiv.focus()将试图把重点放在所有的人(这是不可能的)而且显然只是关注最后一个。

尝试使用.first()方法来筛选下来到你想要什么:emptyDiv.first().focus()

这里是我建议的重新写入:

//Select some elements once 
var $registerErrors = $('#register-errors'); 
var $errorsMsg = $('#error-text'); 

//click the registed button 
$('#register-btn').click(function(){ 
    var $emptyInputs = $('.add-listing-input').filter(function() { 
     return this.value == ""; 
    }); 

    if($emptyInputs){ 
     var $firstEmptyInput = $emptyInputs.first(); 

     var bottomPosition = $firstEmptyInput.position().top + $firstEmptyInput.height() +25; 
     var inputId = $firstEmptyInput.attr('id'); 

     $registerErrors 
      .css('top', bottomPosition) 
      .show(); 

     $errorsMsg.text('Your '+ inputId +' is missing, please fill in'); 

     $firstEmptyInput 
      .focus() 
      .one('keydown', clearError); //this event only fires once! 
    }else{ 
     clearError(); 
     checkEmails(); 
    } 
}); 

function clearError(){ 
    $registerErrors.hide(); 
    $errorsMsg.text(''); 
} 
+0

感谢,简单好用 – rpsep2 2013-02-24 20:56:57