Count length of one input field and print it in another with Gravity Forms and Javascript

こ雲淡風輕ζ 提交于 2019-12-04 06:35:51

问题


I am using Gravity Forms for Wordpress and I am trying to figure out how to count the length of characters a user types into one of my input boxes and print that number to another input box in the same form. I think this can be done with Javascript but I am a total newb and well here is my very watered down effort. Just so you can see what I am trying to do.

<!-- edited -->
 <form>
  <input name="input_10" id="input_1_10" type="text" value="" class="small" tabindex="1">
  <input name="input_2" id="input_1_2" type="text" value="" class="medium" tabindex="2">
  <div style="padding:10px 15px; font-family:sans-serif !important;">
     <p id="preview" style="text-align:center;font-size:22px;font-weight:bold;">Sample Text</p>
  </div>
</form>

<script>
    var bank = document.getElementById("input_1_2");
    var countNum = document.getElementById("input_1_10");
    bank.addEventListener("keyup", function(e) {
        countNum.value = bank.value.length;
    });

    document.getElementById("preview").innerHTML= countNum.value;




</script>

So the user will type their "message" in #input_1_10 and i need a way to count the characters(preferably without counting spaces) and print them in #input_1_2 before the user submits the form.

** EDIT: I would also like to know how to write the value of #input_1_2 in to the paragraph with the ID of #preview. **

Thanks for looking ;)


回答1:


Add an eventListener to the first input. In this case, whenever the user presses and releases a key, the length of the input will be displayed in the second input.

<form>
    <input name="input_10" id="input_1_10" type="text" value="" class="small" tabindex="1">
    <input name="input_2" id="input_1_2" type="text" value="" class="medium" tabindex="2">
</form>

<script>
    var bank = document.getElementById("input_1_10");
    var countNum = document.getElementById("input_1_2");
    bank.addEventListener("keyup", function(e) {
        countNum.value = bank.value.length;
    });
</script>


来源:https://stackoverflow.com/questions/18198117/count-length-of-one-input-field-and-print-it-in-another-with-gravity-forms-and-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!