簡體   English   中英

如何使用jQuery按Tab鍵進行驗證

[英]How to validate on pressing tab key using jquery

我想在按下tab按鈕的同時驗證我的jsp字段。如何使用jquery實現它。

下面是我的jsp頁面

<form:form method="POST"  commandName=" test"  name="testname"  onclick="submitForm();" >   

<div>
<form:input path="testpath" type="text" class="values " name="tpath" id="code"/>
</div>

<div>
<form:input path="testname" type="text" class="values " name="tname" id="name"/>

</div>

<div>
<input type="submit" value="Register">
</div>

</form:form>

jQuery的

function submitForm(){  
    $('form').on('submit', function (e) {
        alert("test");
        var focusSet = false;
        if (!$('#tpath').val()) {
            if ($("#tpath").parent().next(".validation").length == 0) // only add if not added
            {

                 $("#tpath").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter the code</div>");
            }
            e.preventDefault(); 
            $('#tpath').focus();
            focusSet = true;
        } else {
            $("#tpath").parent().next(".validation").remove(); // remove it
        }
        if (!$('#name').val()) {
            if ($("#name").parent().next(".validation").length == 0) // only add if not added
            {
                $("#name").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter seasoname</div>");
            }
            e.preventDefault(); // prevent form from POST to server
            if (!focusSet) {
                $("#name").focus();
            }
        } else {
            $("#name").parent().next(".validation").remove(); 
        }
    });  
}   

在按鈕上單擊僅我的表單驗證。如何通過單擊內部表單進行驗證。

用這個

$('#tpath').keyup();

這在釋放鍵事件上觸發。

捕獲keycode並在元素上編寫keypress event ,如下所示:

//Combine keypress for both the elements as below
$("#tpath,#name").on('keypress',function(e){
    if(e.which==9 && !$(this).val())
         if ($(this).parent().next(".validation").length == 0) 
         {
            $(this).parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter the code</div>");
         }
         else {
            $(this).parent().next(".validation").remove(); // remove it
        }
        $(this).focus();
});
$('#tpath').keyup(function(e) {
    e.keyCode; // this value
    if(e.keyCode == 9){
      //e.keyCode is 9 mean tab is pressed
      // write your validation code over here.
    }
});

我認為這段代碼可以為您工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM