How to count lengths of multiple text inputs and print them into corresponding number fields with Gravity Forms

325 views Asked by At

I'm trying to count the number of characters entered into 4 text input fields and print the character count into their corresponding number fields like so:

  • Character count text input1 -> Number field 1
  • Character count text input2 -> Number field 2
  • Character count text input3 -> Number field 3
  • Character count text input4 -> Number field 4

I found this code snippet in another answer, but its just working for a single input field: Count length of one input field and print it in another with Gravity Forms and Javascript:

<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>

As I'm a total newbie to javascript and jQuery, I don't know how to modify this snippet to get it working. Any ideas or suggestions?

Thanks for your help!

1

There are 1 answers

2
azs06 On

You could repeat repeat addEventListener for all inputs, or you could do it like this

var inputs = document.querySelectorAll('.small');

inputs.forEach(function(input){
 input.addEventListener('keyup', function(e){
  this.nextElementSibling.value = this.value.length;
 })
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Input Demo</title>
</head>
<body>
<label for="inputOne">Input One</label> 
<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">
<hr/> 
<label for="inputTwo">Input Two</label> 
<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">
 
</body>
</html>

Notice, this code depends on the html markup, so it worn't work if you have anything else between two inputs, nextElementSibling selects the next element from current node. nextElementSibling on mdn