2012-10-30 39 views
0

當用戶輸入輸入時,我的textarea可以計算字符串/字符。這裏是我的jsfiddle用條件計數字符串使用jquery

我的問題是,我想在字符串/字符是158以上設定條件的意思是,我想展示裏面<div id="message">We will deduct 2 credit from your account</div>和相同的消息時字符串/字符是316上述消息將更新並顯示< div id="message">We will deduct 3 credit from your account</div>和繼續。 。

實施例:

158 *2 

158 = We will deduct 2 credit from your account 
316 = We will deduct 3 credit from your account 
474 = We will deduct 4 credit from your account 
632 = We will deduct 5 credit from your account 
... 

回答

2

試試吧

$('#myInput').keyup(function() { 
    $('#charCount').text(this.value.length); 

    var c = parseInt(this.value.length/158); 
    if(c > 0) 
     $('#message').text('We will deduct '+c+' credit from your account'); 
});​ 
+0

感謝,工作就像一個魅力:d – rusly

+0

但爲什麼當我刪除字符串/字符信息不更新? – rusly

+1

我已經更新了您的jsfiddle => http://jsfiddle.net/nrkXG/9/ – ke20

0

1)發現字符串的

長度

2)由158

除以它

3)加 '1' 的答案

4)使用字符串連接創建消息 - 「我們將扣除」(3)+ +輸出 「信貸從您的賬戶」

5)的jQuery( 「#message」)。html(「我們將扣除」+(3)+的輸出)「;

0

試試這個

$('#myInput').keyup(function() { 
    var len = this.value.length ; 
    $('#charCount').text(len); 
    var creditCount = 158; 
    if(len > creditCount){ 
     var credits = Math.floor(len/creditCount); 
     $('#message').html('We will deduct '+ credits + ' credit from your account;') 
    } 
});​ 

Check DEMO

+1

第4行的演示中存在拼寫錯誤。也許您期望的代碼是「var creditCount = 158;」? – caoxudong

+0

它實際上不是一個錯字..只用一個較小的輸入測試我的代碼:)修正了 –

0
上textarea的KEYUP你可以檢查沒有

。的字符呈現,因此您可以編寫if-else條件來顯示消息。

檢查:working fiddle

$('#myInput').keyup(function() { 
    if(this.value.length<=158) 
    $('#charCount').text('We will deduct 1 credit from your account'); 
    else if(this.value.length>158 || this.value.length<316) 
    $('#charCount').text('We will deduct 2 credit from your account'); 
    else if(this.value.length>316|| this.value.length<316) 
    $('#charCount').text('We will deduct 3 credit from your account'); 
});​ 
0
$('#myInput').keyup(function() { 
    $('#charCount').text(this.value.length); 
    var length = this.value.length; 
    if (length % 158 == 0) { 
     $('#message').html('We will deduct '+ (length/158) + 
         ' credit from your account;')       
    } 
});