Javascript在表单输入框中自动计数字符并在表单数量输入框中输入结果

Javascript to automatically Count Characters in Form Input Box and Enter result in Form Quantity Input Box?

本文关键字:输入 表单 结果 字符 Javascript 数字      更新时间:2023-09-26

我有一个工作的javascript,将自动计数字符的TextArea和输入结果在另一个文本区域。

然而,我正试图修改此工作与现有的购物车表单,在这种形式下,它必须在一个失败。

这个表单有一个区域供客户输入文本,脚本将对字符进行计数,结果数字是客户购买的商品数量。

下面是我的代码在哪里工作的例子。包括我的购物车表单的缩短示例。

我怎样才能使它与表单一起工作?

这是我的javascript:

<script type="text/javascript">
function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
</script>
这是我的HTML:
<body>
    <!-- This example updates correctly to a <textarea> HOWEVER, it needs to work with a Form <input type="text";> as shown below -->
    <textarea id="enter-your-text-input" onkeyup="countChars('enter-your-text-input','character-count-input');" name="product1[]" maxlength="200" value="" style="position:absolute; left:27px; top:28px; width:320px; color:#4B4B4B; font-size:18.0px; height:26px; width:320px;/*Tag Style*/"></textarea>
    <textarea id="character-count-input" name="qty1" value="characters" style="position:absolute; left:247px; top:72px; width:100px; color:#4B4B4B; font-size:18.0px; height:26px; width:100px;/*Tag Style*/"></textarea>
    <!-- I NEED to Count the Characters and display the results in this form-->
    <form id="shopping-cart-form" onsubmit="return validate_shopping-cart-form(this)" action="http://www.someaddress.com" method="post" target="cart" style="margin:0;position:absolute;left:0px;top:120px;width:372px;height:546px;">
        <input type="text" id="enter-your-text-input" onkeyup="countChars('enter-your-text-input','character-count-input');" name="product1[]" maxlength="200" value="" style="position:absolute; left:27px; top:28px; width:320px; color:#4B4B4B; font-size:18.0px; height:26px; width:320px;/*Tag Style*/"></textarea>
        <input type="text" id="character-count-input" name="qty1" value="characters" style="position:absolute; left:247px; top:72px; width:100px; color:#4B4B4B; font-size:18.0px; height:26px; width:100px;/*Tag Style*/"></textarea>
    </form>
</body>   

对于<input>元素,您需要通过.value分配值,以下是正确的代码:

function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).value = len;
}