2014-09-02 122 views
-2

我想用jQuery驗證輸入字段。我想檢查該字段的val();爲5個以上,或者如果該字段的值小於2jQuery - 如果語句,結合兩個IF的

目前,這是我有:

$('#customamount').keyup(function() { 
    $('.amount-field').text($(this).val()); 
    if($(this).val() > 5){ 
     $(this).addClass("error"); 
     $(this).prop("title","Whoops! Too high"); 
     $(this).tooltip('toggle'); 
    }else{ 
     $(this).removeClass("error").addClass("success"); 
     $(this).attr("title","Good!"); 
     $(this).tooltip('toggle');  
    } 
    if($(this).val() < 2){ 
     $(this).addClass("error"); 
     $(this).prop("title","The minimum amount is 2."); 
     $(this).tooltip('toggle'); 
    }else{ 
     $(this).removeClass("error").addClass("success"); 
     $(this).attr("title","Good!."); 
     $(this).tooltip('toggle');  
    } 
}); 
<input type="text" value="10" id="customamount"> 

目前,它只是將.success類添加到輸入和title="Good!"

如何組合上述兩個IF語句?

+1

這是非常基本的編程曲estion – 2014-09-02 13:35:45

+0

@nagarajub我是jQuery編程新手 - 認爲我可以在這裏獲得一些幫助,儘管它對於大多數人來說是基本的。 – oliverbj 2014-09-02 13:38:52

+2

嘿,你有良好的聲譽(782),解決了很多問題,你怎麼會錯過這個簡單的編程邏輯 – 2014-09-02 13:41:45

回答

4

使用else if

if($(this).val() > 5){ 
     $(this).addClass("error"); 
     $(this).prop("title","Whoops! Too high"); 
     $(this).tooltip('toggle'); 
    } 
    else if($(this).val() < 2){ 
     $(this).addClass("error"); 
     $(this).prop("title","The minimum amount is 2."); 
     $(this).tooltip('toggle'); 
    }else{ 

     $(this).removeClass("error").addClass("success"); 
     $(this).attr("title","Good!."); 
     $(this).tooltip('toggle');  
    } 
0
var $this = $(this); 
var val = $this.val(); 
if(val > 5) { 
    // case for 5 
    return; 
} 
if(val < 2) { 
    // case for 2 
    return; 
} 
// good case 

旁註:緩存你的jQuery的電話。不要重做它們。如果你做了很多事情,那麼這是不必要的工作。

你也應該看看這個: http://jqueryvalidation.org/

不要強調自己與驗證當有使用和功能簡單得多的方式來完成它:)

+0

不要重複如果像那。這使得它不易維護。 – Cerbrus 2014-09-02 13:47:21

+0

是真的。改變了它 – Dbl 2014-09-02 14:03:50

1

可以清理else if,對於$(this)臨時變量,方法鏈接和移動重新使用的代碼出if語句:

$('#customamount').keyup(function() { 
    var t = $(this); // Only convert `this` to a jQuery object once. 
    $('.amount-field').text(t.val()); 

    if(t.val() > 5) { 
     t.addClass("error") 
     .prop("title","Whoops! Too high"); 
    } else if(t.val() < 2) { 
     t.addClass("error") 
     .prop("title","The minimum amount is 2."); 
    } else { 
     t.removeClass("error").addClass("success") 
     .attr("title","Good!"); 
    } 
    t.tooltip('toggle'); //Whatever the value of `t.val()`, this should be called. 
});