Javascript字符或数字计数

时间:2017-08-31 15:01:45

标签: javascript html

我们如何计算javascript中文本框中输入的字符数? 让我知道我错过了什么。



function count1() {
  var len = Number(document.getElementById("num1").value);
  var n = len.length;
  document.getElementById("demo1").innerHTML = n;
}

<!doctype html>
<html>
  <head></head>
  <body>
    Enter Num: <input id="num1">
    <button onclick="count1()">Try it</button>
    <input id="demo1">
  </body>
</html>
&#13;
&#13;
&#13;

6 个答案:

答案 0 :(得分:2)

不需要Number&amp;将innerHTML替换为value,这是输入的适当属性。Number的主要目标是将参数转换为数字。例如"1"这是一个字符串将是已转换为1,但无法将字母或字符转换为数字。在您的情况下,如果您使用数字,它将返回NaN

&#13;
&#13;
function count1() {
  var len = (document.getElementById("num1").value).length;
  document.getElementById("demo1").value = len;
}
&#13;
Enter Num: <input id="num1">
<button onclick="count1()">Try it</button>
<input id="demo1">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您只需要获取第一个输入https://issues.apache.org/jira/browse/LOG4J2-1548length并将其设置为第二个输入value  (而不是使用value):

&#13;
&#13;
function count1() {
  var len = document.getElementById('num1').value.length;
  document.getElementById("demo1").value = len;
}
&#13;
<!doctype html>
<html>
  <head></head>
  <body>
    Enter Num: <input id="num1">
    <button onclick="count1()">Try it</button>
    <input id="demo1">
  </body>
</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以直接获取字符串和length属性,以指定文本字段的value属性。

function count1() {
    document.getElementById("demo1").value = document.getElementById("num1").value.length;
}
Enter Num: <input id="num1">
<button onclick="count1()">Try it</button>
<input id="demo1">

答案 3 :(得分:0)

  

Number()函数无法使用!
  并使用value代替innerHTML来更改输入元素文本

&#13;
&#13;
function count1() {
  var len = document.getElementById("num1").value;
  var n = len.length;
  document.getElementById("demo1").value = n.toString();
}
&#13;
<html>
<head>
</head>
<body>
Enter Num: <input id="num1">
<button onclick="count1()">Try it</button>
  <input id="demo1">
</body>
</html>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

试试这个

JS

function count1() {
   var len = (document.getElementById("num1").value).length;
   document.getElementById("demo1").value = len;
}

HTML

Enter Num: <input id="num1">
<button onclick="count1()">Try it</button>
<input id="demo1">

答案 5 :(得分:0)

以下是javascript中的一个示例,用于在您键入时更新文本输入的计数:

&#13;
&#13;
document.querySelector('input[name="firstname"]').oninput=updateCount;
function updateCount(event) {
    var countSpan = document.querySelector('span#count');
    countSpan.textContent = event.target.value.length;
}
&#13;
<label for="firstname">First Name</label>
<input name="firstname" type="text"/>
<div>
  Your first name has <span id="count">0</span> letters.
</div>
&#13;
&#13;
&#13;