我如何在一系列输入中制作标签并输入相同的表现



我在一系列输入框上执行一些验证。我需要确保输入的值可以除以6。

当用户试图提交无效的值时,所有其他输入将被禁用,直到纠正错误,并且DIV弹出了解释问题。

我尝试的第一种方法是捕获选项卡的关键事件或输入:

$(".test1").keyup(function(event) {
  if((event.keyCode == 9) || (event.keyCode == 13)) {
     event.preventDefault();      
   var valid = true;
   if(parseInt($(this).val()) % 6 != 0){
    valid = false;
    $('#errorMessage').html("That's not divisible by 6");
   }
   if (!valid){
    // Show error message and disable other text boxes
    var position = $(this).position();
    $('input').not(this).prop('disabled', true);
    $("#validation").show();
    $("#validation").offset({top:position.top, left:position.left + $(this).width()});
   } else {
    // Hide error message and enable other text boxes
    $("#validation").delay(200).hide();
    $('input').not(this).prop('disabled', false);
    $(this).parent().next().find('.test1').focus();
   } 
  }
 });

当用户与Enter提交时,这可以正常工作,但是如果他们标记了,则可以执行以下操作:

  • 如果通过了验证,它将在下一个文本框中再次触发
  • 如果验证失败,焦点仍然移至下一个文本框
  • 如果验证失败(并且用户已按ENTER(在用户纠正验证时,当使用选项卡重新提交
  • 重新提交时,则不会删除错误div

第二种方法是使用更改事件:

$(".test2").change(function(){
 var valid = true;
 if(parseInt($(this).val()) % 6 != 0){
  valid = false;
  $('#errorMessage').html("That's not divisible by 6");
 }
 if (!valid){
  // Show error message and disable other text boxes
  var position = $(this).position();
  $('input').not(this).prop('disabled', true);
  $("#validation").show();
  $("#validation").offset({top:position.top, left:position.left + $(this).width()});
 } else {
  // Hide error message and enable other text boxes
  $("#validation").delay(200).hide();
  $('input').not(this).prop('disabled', false);
  $(this).parent().next().find('.test2').focus();
 } 
});

这也可以与Enter一起使用,但是如果用户纠正错误后按下选项卡,则不将焦点传递到下一个文本框上。

请参阅https://jsfiddle.net/bdgriffiths/sqrugh63/3/

(我还尝试使用:

执行验证
$('.test').on('input', function() {  ...Do the validation... }

可以正常工作,但是在每次击键后都会触发。即,在输入" 12"时,误差将在按下" 1"之后触发 - 这会令人讨厌。(

事实证明它正在禁用其他正在拧紧此的输入。

通过创建CSS类以使其他输入 LOOK 禁用:

来解决问题:
.disabledClass {
  background-color: #eee;
  color: #ccc;
  border: 1px solid #ccc;
}

,然后迫使焦点保持在单元格中,直到纠正验证误差为止:

$(this).focus().select();

所以整个功能现在看起来像这样:

$(".test2").blur(function() { 
    var valid = true;
    if (parseInt($(this).val()) % 6 != 0) {
      valid = false;
      $('#errorMessage').html("That's not divisible by 6");
    }
    if ((valid) || (!($(this).val()))) { // valid or blank
      // Hide error message and enable other text boxes
      $("#validation").fadeOut(500);
      $('input').not(this).removeClass('disabledClass');
    } else { // not valid
      // Show error message and disable other text boxes
      var position = $(this).position();
      $('input').not(this).addClass('disabledClass');
      $("#validation").fadeIn(500);
      $("#validation").offset({
        top: position.top,
        left: position.left + $(this).width()
      });
      $(this).focus().select();
    }
  });

https://jsfiddle.net/bdgriffiths/sqrugh63/9/

最新更新