简体   繁体   English

jQuery或Javascript计算字符,如果不等于20,则在两个字段中

[英]Jquery or Javascript to count chars and if not equal to 20 in two fields

我一直在寻找一个脚本来计算2个文本区域中的字符,如果它不等于20个字符,则会在20个字符后添加“空格”。

var combined = $('#first').val() + $('#second').val();

while (combined.length < 20) 
{
    combined += ' ';
}

alert(combined);

JSFiddle DEMO JSFiddle演示

You can loop through the text in the textarea and keep padding it until it is 20 in length. 您可以遍历文本区域中的文本,并继续填充直到其长度为20。

HTML : HTML

<textarea></textarea>
<textarea></textarea>
<a id="pad" href="#">Pad to 20</a>

jQuery : jQuery的

$("#pad").click(function(){
$("textarea").each(function(index, element){
    while(this.value.length < 20){
        this.value = this.value + " ";     
    }
});

});​ });

Try it out! 试试看!

This would take an input string and create a 20-char min string from it. 这需要一个输入字符串,并从中创建一个20个字符的最小字符串。

<script type="text/javascript">
    function pad_right(s){
        if(s.length < 20){
            for (var i = 0; i < 20 - s.length; i++) {
                s += " ";
            }
        }
        return s;
    }
</script>
function padString (text, length) {
    while (text.length < length)
        text = text + ' ';
    return text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM