0

我正在做一个简单的表单验证,它简单地检查是否填写了高度字段。我已经仔细检查了我的代码中的所有内容,但我找不到它为什么不起作用。

我的 HTML:

<form id="configuration" action="">

   <div class="con_near">
      <label for="height">height: (mm)</label>
      <input id="form_height" name="height" maxlength="4" type="text" />
   </div><!--End con_near-->

   <input name="calculated" type="submit" class="submit" value="Calculate" />

</form>

我的 jQuery:

    <script>

    $(document).ready(function(){  

    // Form validation
    var configForm = $("#configuration");
    var height = $("#form_height");

    // On blur
    height.blur(validateHeight);

    // On keyup
    height.keyup(validateHeight);

    configForm.submit(function(){
        if(validateHeight())
            return true;

        else
            return false;

    });         

    function validateHeight() {
        if(height.val().length() < 4) {
            height.addClass("red_border");  
            return false;
        }
        else{
            height.removeClass("red_border");
            return true;    
        }
    }

    });

       </script>
4

5 回答 5

2

长度不是函数而是属性

尝试

configForm.submit(function(){
    if(validateHeight(height))
        return true;

    else
        return false;

});     
function validateHeight(height) {
    if(height.val().length < 4) {
        height.addClass("red_border");  
        return false;
    }
    else{
        height.removeClass("red_border");
        return true;    
    }
}
于 2013-10-24T12:00:57.440 回答
1

问题就在这里.length()

采用

if(height.val().length < 4) {

代替

if(height.val().length() < 4) {
于 2013-10-24T12:02:43.993 回答
0

使用length代替length()like,

if(height.val().length < 4) {

代替

if(height.val().length() < 4) {

function validateHeight(height) {
    if(height.val().length < 4) {
    .....

演示

于 2013-10-24T12:04:17.503 回答
0

提交事件不会通过返回 false 来停止您需要使用 preventDefault() 来停止事件尝试此代码

configForm.submit(function(e){
    if(!validateHeight())
        e.preventDefault();
});         

function validateHeight() {
    if(height.val().length < 4) { // <- here you also made a mistake in length its a property not a function
        height.addClass("red_border");  
        return false;
    }
    height.removeClass("red_border");
    return true;
}
于 2013-10-24T12:06:57.713 回答
0

尝试这样的事情

$(document).ready(function(){

    // Form validation
    var configForm = $("#configuration");
    var height = $("#form_height");

    // On blur
    height.blur(validateHeight);

    // On keyup
    height.keyup(validateHeight);

    configForm.submit(function(){
        return validateHeight();
    });

    function validateHeight() {
        if(height.val().length < 4) {
            height.addClass("red_border");
            return false;
        }
        else{
            height.removeClass("red_border");
            return true;
        }
    }

});
于 2013-10-24T12:07:38.917 回答