【问题标题】:Javascript to auto calculate total character in input fieldJavascript自动计算输入字段中的总字符
【发布时间】:2023-03-04 16:15:01
【问题描述】:

我有一个问题要解决。这是我到目前为止所拥有的,它似乎可以按原样工作,但是当我添加一个 php 变量以自动填充输入字段时,它似乎没有计算所使用的字符。

此字段的最大值为 80 个字符,我无法控制。我必须限制它最多 80 个字符。一旦表单加载并填充了字段,我需要输入字段来自动计算。当我将 php 变量包含到输入值中时,输入字段显示该字段填充了字符但是,该字段保持在“零”字符,直到我将鼠标移动到该字段中并尝试添加另一个字符。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script type="text/javascript">
document.testform.countInput.focus();
function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
</script>

<form id="testform">
Title: <strong id="countOutput">0</strong><strong>/80 Max Character</strong>
<input  type="text" name="dsp_URL" value="" size="80" maxlength="80"  lengthcut="true" id="countInput" onkeyup="countChars('countInput','countOutput');" /><br />
</form>

<script type="text/javascript">


var input = document.getElementById ("countInput");
input.focus ();
</script>
<body>
</body>
</htmt>

【问题讨论】:

  • 您的代码不包含任何 PHP,因此不清楚您在问什么。请注意,在运行任何 JavaScript 之前,PHP 是在服务器端处理的。页面返回给客户端后就不能使用PHP代码了。
  • 另外,document.getElementById(countfrom).value.length != document.getElementById(countfrom).value
  • php 变量将进入我忽略的 value="$url" 中。但是在测试时它不起作用。
  • 您需要做以下两件事之一:(1)在页面加载时输出您想要的长度(例如,&lt;?php echo strlen($url); ?&gt;)或(2)在页面加载时调用 JavaScript 函数。在 JavaScript 触发之前,它将是 0 或任何您预填充的内容。
  • 得到它的工作人员。感谢您的意见。

标签: javascript count character


【解决方案1】:

您应该在页面加载时调用该函数以及onkeyup 事件

document.testform.countInput.focus();

function countChars(countfrom, displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
<head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
</head>

<form id="testform">
  Title: <strong id="countOutput">0</strong><strong>/80 Max Character</strong>
  <input type="text" name="dsp_URL" value="" size="80" maxlength="80" lengthcut="true" id="countInput" onkeyup="countChars('countInput','countOutput');" />
  <br />

  <script>
    countChars('countInput', 'countOutput');
  </script>

</form>

<body>
</body>

只需确保在调用 countChars 之前对其进行定义。

【讨论】:

    【解决方案2】:

    我认为可以安全地假设通过 php 用字符串填充文本字段不会触发 countChars() 的条件,因为它的触发器是该文本字段上的 onkeyup。

    也许您可以在How to impose maxlength on textArea in HTML using JavaScript 中找到对您的问题有帮助的解决方案。我希望这有助于您的验证:)

    【讨论】:

    • 我可以使用其他事件来触发它吗?我在这里迷路了。
    猜你喜欢
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    相关资源
    最近更新 更多