使用 JavaScript 显示 HTML 文本框中剩余的字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12742595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:09:18  来源:igfitidea点击:

Show how many characters remaining in a HTML text box using JavaScript

javascripttextarea

提问by ChristineS

This is my code:

这是我的代码:

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, 160);
        field.blur();
        field.focus();
        return false;
    } else {
        countfield.value = maxlimit - field.value.length;
    }
}

How can I display how many characters are remaining from a certain text box with a limit of 160?

如何显示限制为 160 的某个文本框中剩余的字符数?

回答by Nokia808Freak

Dynamic HTML element functionThe code in herewith a little bit of modification and simplification:

动态 HTML 元素函数这里的代码稍作修改和简化:

<input disabled  maxlength="3" size="3" value="10" id="counter">
<textarea onkeyup="textCounter(this,'counter',10);" id="message">
</textarea>
<script>
function textCounter(field,field2,maxlimit)
{
 var countfield = document.getElementById(field2);
 if ( field.value.length > maxlimit ) {
  field.value = field.value.substring( 0, maxlimit );
  return false;
 } else {
  countfield.value = maxlimit - field.value.length;
 }
}
</script>

Hope this helps!

希望这可以帮助!

tip:

提示:

When merging the codes with your page, make sure the HTML elements(textarea, input) are loaded first before the scripts (Javascript functions)

将代码与您的页面合并时,请确保在脚本(Javascript 函数)之前首先加载HTML 元素 ( textarea, input)

回答by Anoop

You can bind key press event with your input box and returning falseif characters are more than 160 will solve the problem jsfiddle.

您可以将按键事件与输入框绑定,false如果字符超过 160 则返回将解决jsfiddle问题。

JavaScript:

JavaScript:

$('textarea').keypress(function(){

    if(this.value.length > 160){
        return false;
    }

    $("#remainingC").html("Remaining characters : " + (160 - this.value.length));
});?

HTML

HTML

<textarea></textarea>?
<span id='remainingC'></span>

回答by cjbrog

Included below is a simple working JS/HTML implementation which updates the remaining characters properly when the input has been deleted.

下面包括一个简单的 JS/HTML 实现,它在输入被删除时正确更新剩余的字符。

Bootstrap and JQuery are required for the layout and functionality to match. (Tested on JQuery 2.1.1 as per the included code snippet).

布局和功能需要 Bootstrap 和 JQuery 才能匹配。(根据包含的代码片段在 JQuery 2.1.1 上测试)。

Make sure you include the JS code such that it is loaded after the HTML. Message me if you have any questions.

确保包含 JS 代码,以便在 HTML 之后加载它。如果您有任何问题,请给我留言。

Le Code:

乐码:

$(document).ready(function() {
  var len = 0;
  var maxchar = 200;

  $( '#my-input' ).keyup(function(){
    len = this.value.length
    if(len > maxchar){
        return false;
    }
    else if (len > 0) {
        $( "#remainingC" ).html( "Remaining characters: " +( maxchar - len ) );
    }
    else {
        $( "#remainingC" ).html( "Remaining characters: " +( maxchar ) );
    }
  })
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="row">
  <div class="col-sm-6 form-group">
    <label>Textarea</label>
    <textarea placeholder="Enter the textarea input here.. (limited to 200 characters)" rows="3" class="form-control" name="my-name" id="my-input" maxlength="200"></textarea><span id='remainingC'></span>
  </div>
</div> <!--row-->

回答by Christoph

Just register an Eventhandler on keydownevents and check the length of the input field on that function and write it into a separate element.

只需在keydown事件上注册一个 Eventhandler并检查该函数上输入字段的长度并将其写入一个单独的元素。

See the demo.

请参阅演示

var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;

i.addEventListener("keydown",count);

function count(e){
    var len =  i.value.length;
    if (len >= maxchar){
       e.preventDefault();
    } else{
       c.innerHTML = maxchar - len-1;   
    }
}
?

You should check the length on your server too, because Javascript might be disabled or the user wants to do something nasty on purpose.

您也应该检查服务器上的长度,因为 Javascript 可能被禁用或者用户想要故意做一些令人讨厌的事情。

回答by Manjunath Akalawadi

Try this

尝试这个

HTML

HTML

<textarea id="textarea" rows="8" cols="50" maxlength="100" ></textarea>
<div id="feedback"></div>

JS

JS

$(document).ready(function() {
        var max = 1000;
        $('#feedback').html(max + 'characters remaining');

        $('#textarea').keyup(function() {
            var text_length = $('#textarea').val().length;
            var text_remaining = max - text_length;

            $('#feedback').html(text_remaining + ' characters remaining');
        });
    });

回答by Nokia808Freak

Try the following code for instance:

例如,尝试以下代码:

working code in jsfiddle.net

jsfiddle.net 中的工作代码

For textArea, use this:

对于 textArea,使用这个:

<textarea id="txtBox"></textarea>
...
...

For textBox, use this:

对于文本框,使用这个:

<input type="text" id="txtBox"/>
<br>
<input type="text" id="counterBox"/>
<script>
 var txtBoxRef = document.querySelector("#txtBox");
 var counterRef = document.querySelector("#counterBox");
 txtBoxRef.addEventListener("keydown",function(){
  var remLength = 0;
  remLength = 160 - parseInt(txtBoxRef.value.length);
  if(remLength < 0)
   {
    txtBoxRef.value = txtBoxRef.value.substring(0, 160);
    return false;
   }
  counterRef.value = remLength + " characters remaining...";
 },true);
</script>

Hope this Helps!

希望这可以帮助!

回答by Richard Ev

How about this approach, which splits the problem into two parts:

这种方法如何,它将问题分为两部分:

  • Using jQuery, it shows a decrementing counter below the textarea, which turns red when it hits zero but still allows the user to type.
  • I use a separate string length validator (server and client-side) to actually prevent submission of the form if the number of chatacters in the textareais greater than 160.
  • 使用 jQuery,它在 下方显示一个递减计数器textarea,当它达到零时变为红色,但仍允许用户输入。
  • 如果字符数textarea大于 160,我使用单独的字符串长度验证器(服务器端和客户端)来实际阻止提交表单。

My textareahas an id of Message, and the spanin which I display the number of remaining characters has an id of counter. The css class of errorgets applied when the number of remaining characters hits zero.

Mytextarea的 id 为Messagespan我在其中显示剩余字符数的 id 为countererror当剩余字符数达到零时,将应用css 类。

var charactersAllowed = 160;

$(document).ready(function () {
    $('#Message').keyup(function () {
        var left = charactersAllowed - $(this).val().length;
        if (left < 0) {
            $('#counter').addClass('error');
            left = 0;
        }
        else {
            $('#counter').removeClass('error');
        }
        $('#counter').text('Characters left: ' + left);
    });
});

回答by Lucky

try this code in here...this is done using javascript onKeyUp() function...

在此处尝试此代码...这是使用 javascript onKeyUp() 函数完成的...

<script>
function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
length=0;  
text='<span class="disable"> '+text+' <\/span>';  
entranceObj.value=entranceObj.value.substr(0,characters);  
}  
exitObj.innerHTML = text.replace("{CHAR}",length);  
}
</script>

textarea counter demo

textarea 计数器演示

回答by cnom

I needed something like that and the solution I gave with the help of jquery is this:

我需要这样的东西,我在 jquery 的帮助下给出的解决方案是这样的:

<textarea class="textlimited" data-textcounterid="counter1" maxlength="30">text</textarea>
<span class='textcounter' id="counter1"></span>

With this script:

使用这个脚本:

// the selector below will catch the keyup events of elements decorated with class textlimited and have a maxlength
$('.textlimited[maxlength]').keyup(function(){
     //get the fields limit
    var maxLength = $(this).attr("maxlength");

    // check if the limit is passed
    if(this.value.length > maxLength){
        return false;
    }

    // find the counter element by the id specified in the source input element
    var counterElement = $(".textcounter#" + $(this).data("textcounterid"));
    // update counter 's text
    counterElement.html((maxLength - this.value.length) + " chars left");
});

Α live demo Here

现场演示在这里

回答by Gleb Umarov

HTML:

HTML:

 <form>
  <textarea id='text' maxlength='10'></textarea>
  <div id='msg'>10 characters left</div>
  <div id='lastChar'></div>
</form>

JS:

JS:

function charCount() {
  var textEntered = document.getElementById('text').value;
  var msg = document.getElementById('msg');
  var counter = (10-(textEntered.length));
  msg.textContent = counter+' characters left';
}

var el = document.getElementById('text');
el.addEventListener('keyup',charCount,false);