2017-01-03 32 views
0

我正在嘗試使用JQuery製作動態表單,當用戶在表單的輸入中輸入少於4個字符時,我想要顯示錯誤消息和顏色。在JQuery中,如何僅根據一個表單輸入的值顯示錯誤?

HRE是我的代碼:

<form> 

    <label for="text">Text </label> 
    <input id="text" type="text"> 

    <label for="text2">Text 2</label> 
    <input id="text2" type="text"> 

    <button type="submit">Send</button> 

    <div class="alert alert-block alert-danger" style="display:none"> 

     <h4>Error!</h4> 

     You have to enter less than 4 caracters in the 2nde input ! 

    </div> 

    </form> 

<script src="bootstrap/js/jquery.js"></script> 
<script> 
    $(function(){ 
    $("form").on("submit", function() { 
     if($("input:text2").val().length < 4) { 
     $("div.form-group").addClass("has-error"); 
     $("div.alert").show("slow").delay(4000).hide("slow"); 
     return false; 
     } 
    }); 
    }); 
</script> 

但似乎只有在第一次輸入的值小於4個字母出現錯誤信息,但我希望它出現時, 2nd輸入少於4個字母。

感謝

回答

1

相反的:

$("input:text2"); 

您的意思是:

$("#text2") 

?我不確定前者的含義,但後者是第二個文本輸入ID的ID選擇器。

0

嘗試在jQuery的

if($("#text2").val().length < 4) 

$("form").on("submit", function() { 
 
     if($("#text2").val().length < 4) { 
 
     $("div.form-group").addClass("has-error"); 
 
     $("div.alert").show("slow").delay(4000).hide("slow"); 
 
     return false; 
 
     } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form> 
 

 
    <label for="text">Text </label> 
 
    <input id="text" type="text"> 
 

 
    <label for="text2">Text 2</label> 
 
    <input id="text2" type="text"> 
 

 
    <button id="submitButton" type="submit">Send</button> 
 

 
    <div class="alert alert-block alert-danger" style="display:none"> 
 

 
     <h4>Error!</h4> 
 

 
     You have to enter less than 4 caracters in the 2nde input ! 
 

 
    </div> 
 

 
    </form>

使用id選擇
相關問題