2017-10-20 53 views
1

以下是我的代碼。我想要做的就是添加驗證,因此當用戶點擊輸入字段時,會顯示驗證消息「需要名稱」。然而在那一刻,它只是在輸入字段下方,並且一直在那裏。謝謝試圖添加jQuery驗證而不提交()按鈕

$(document).ready(function(){ 
 
    if($('#firstname').val() == ''){ 
 
    $('.errorMsg').show(); 
 
    } else{ 
 
    $('.errorMsg').hide(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label for="firstname">First Name</label> 
 
<input type="text" name="firstname" id="firstname" placeholder="First name"  maxlength="15" <span class="errorMsg">Name required </span> 
 
</input>

+0

如果這是一個真實世界中的應用,我也建議針對'maxlength'屬性。人們往往比大多數web開發人員可以想象的更有趣的名字 –

+0

@OliverBaumann但是,如果數據庫只接受15,那麼它可能會導致一些麻煩。但我同意15個字符對於名字而言是低的。 – Ivar

+0

@Ivar,如果一個數據庫只接受15個varchars,說實話,數據庫管理員;-),這不是一個參數。顯然沒有冒犯的意思! –

回答

0

您可以使用該blur事件:

$(document).ready(function() { 
 
    $('#firstname').on('blur', function() { 
 
     if ($('#firstname').val() == '') { 
 
      $('.errorMsg').show(); 
 
     } else { 
 
      $('.errorMsg').hide(); 
 
     } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label for="firstname">First Name</label> 
 
<input type="text" name="firstname" id="firstname" placeholder="First name" 
 
    maxlength="15"> <span class="errorMsg" style="display: none;">Name required </span> 
 
</input>

0

使用blur事件,可以直接從找到的元素被稱爲使用jQuery

$(document).ready(function(){ 

    $('.errorMsg').hide(); 

    $('#firstname').blur(function(){ 
    if($('#firstname').val() == ''){ 
     $('.errorMsg').show(); 
    } 
     else{ 
      $('.errorMsg').hide(); 
     } 

    }); 


}); 

這裏有一個JSFiddle

1

使用CSS最初隱藏錯誤消息。您也有無效的HTML:錯誤消息span不能嵌套在輸入中。

工作液:

$(document).ready(function(){ 
 
    $('#firstname').on('blur', function() { 
 
     if($(this).val() === '') { 
 
     $('.errorMsg').show(); 
 
     } else { 
 
     $('.errorMsg').hide(); 
 
     } 
 
    }); 
 
});
.errorMsg { 
 
    display: none; 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label for="firstname">First Name</label> 
 
<input type="text" name="firstname" id="firstname" placeholder="First name" 
 
maxlength="15"/> 
 
<span class="errorMsg">Name required </span>

0

jQuery Blur - 綁定的事件處理程序的 「模糊」 JavaScript事件,或者觸發元素上的事件。

嘗試(JSFiddle

var firstNameInput = $('input#firstname'), 
    errorMsgEl = $('.errorMsg'); 

// Bind blur on the input for 'first name' 
firstNameInput.bind('blur', function() { 
    // Check if input is blank 
    if(firstNameInput.val() == '') { 
     // Ensure error isn't already displayed 
     if (errorMsgEl.length == 0) $("<div class='errorMsg'>Name required</div>").insertAfter(this); 
    } else { 
     errorMsgEl.remove(); 
    } 
});