我如何修改jquery短信计数器

时间:2016-01-28 06:59:21

标签: javascript jquery

我正在使用短信计数器来显示剩余的字符数和短信数,但我想对此进行一些修改,我想要的是在sms>时将最大剩余字符从160更改为145。 1

这是我的代码,总是有160个字符。

<textarea name="message" value="" id="message"></textarea>
<p>
<span id="remaining">160 characters remaining</span>
<span id="messages">1 message(s)</span>
</p>

document).ready(function(){
    var $remaining = $('#remaining'),
    $messages = $remaining.next();

    $('#message').keyup(function(){
        var chars = this.value.length,
        messages = Math.ceil(chars / 160),
        remaining = messages * 160 - (chars % (messages * 160) || messages * 160);

       $remaining.text(remaining + ' characters remaining');
       $messages.text(messages + ' message(s)');
   });
});

3 个答案:

答案 0 :(得分:1)

我认为您需要以下代码

if(messages>1)
    { 



    remaining = (((messages-1) * 145)+160 - chars ); 


    } 

Jsfiddle

答案 1 :(得分:1)

这将有效,我测试了它....

$(document).ready(function(){
var $remaining = $('#remaining'),
$messages = $remaining.next();

$('#message').keyup(function(){
    var chars = this.value.length; 
    if(chars <= 305){
    var messages = Math.ceil(chars / 145);
    var remaining = messages * 145 - (chars % (messages * 145) || messages * 145); 
    }       
    else if(chars <= 160){
    var messages = Math.ceil(chars / 160);
    var remaining = messages * 160 - (chars % (messages * 160) || messages * 160);
    }
    else{ 
    var messages = Math.ceil(chars / 145);
    var remaining = messages * 145 - (chars % (messages * 145) || messages * 145); 
    }
   $remaining.text(remaining + ' characters remaining');
   $messages.text(messages + ' message(s)');
});
});

答案 2 :(得分:0)

很抱歉。 使用我为你编码的那个。 此代码比上一代更准确。

$(document).ready(function(){
var $remaining = $('#remaining'),
$messages = $remaining.next();
var arr = [0, 160, 305, 450, 595, 740, 885, 1030, 1175, 1320, 1465, 1610, 1755, 1900];
$('#message').keyup(function(){
var chars = this.value.length;          
for(var i = 0;i<arr.length;i++){
    if(chars >=arr[i]){
        $messages.text((i+1) + ' message(s)');          
        $remaining.text((arr[(i+1)]-chars) + ' characters remaining');
    }
}
});
});