如何使Tab和Enter在一系列输入中表现相同?

我正在对一系列输入框进行一些validation。 我需要确保输入的值可以被6整除。

当用户尝试提交无效值时,所有其他输入都将被禁用,直到他们更正错误,并弹出一个Div解释问题。

我尝试的第一种方法是捕获Tab或Enter的键盘事件:

$(".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提交时,这可以正常工作,但如果他们选中它,则会执行以下操作:

  • 如果validation通过,它将在下一个文本框中再次触发
  • 如果validation失败,焦点仍会移动到下一个文本框
  • 如果validation失败(并且用户已按下输入),当用户更正它时,使用Tab重新提交时不会删除错误Div

第二种方法是使用Change事件:

 $(".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,但这次如果在用户更正错误后按Tab键,则焦点不会传递到下一个文本框。

见https://jsfiddle.net/bdgriffiths/sqrugh63/3/

(我也尝试使用以下方法执行validation:

 $('.test').on('input', function() { ...Do the validation... } 

哪个工作正常,但每次击键后触发。 即当输入“12”时,错误将在按下“1”后触发 – 这会令人恼火。)

事实certificate它正在禁用正在搞砸的其他输入。

通过创建一个CSS类来解决这个问题,使其他输入看起来被禁用:

 .disabledClass { background-color: #eee; color: #ccc; border: 1px solid #ccc; } 

然后强制焦点停留在单元格中,直到validation错误得到纠正:

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

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

 $(".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/