Home > Software engineering >  Trigger the counter function on page load
Trigger the counter function on page load

Time:10-16

I am using keyup function to calculate the number of words and characters. The function is working fine but when the page loads, initially it does not calculate the default values within the textarea and when any key is pressed then it works fine. I need to trigger the function on page load and calculate the default string This is default text. Here is my code below:

<p> Words <span id="count1">0</span></p>
<p>Characters <span id="count2">0</span></p>
<textarea rows="5" id="mycounter">This is default text</textarea>

<script>
    $(document).ready(function () {
        $("#mycounter").on("keyup", function () {
            var wcounts = 0;
            var ccounts = 0;

            if ((this.value.match(/\S /g)) != null) {
                wcounts = this.value.match(/\S /g).length;
            }
            if ((this.value.match(/\S /g)) != null) {
                ccounts = this.value.length;
            }
            $('#count1').text(wcounts);
            $('#count2').text(ccounts);
        });
    });

Thanks in advance.

CodePudding user response:

You can use trigger to do it

$(document).ready(function () {
        $("#mycounter").on("keyup", function () {
            var wcounts = 0;
            var ccounts = 0;

            if ((this.value.match(/\S /g)) != null) {
                wcounts = this.value.match(/\S /g).length;
            }
            if ((this.value.match(/\S /g)) != null) {
                ccounts = this.value.length;
            }
            $('#count1').text(wcounts);
            $('#count2').text(ccounts);
        });
        $("#mycounter").trigger('keyup');
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> Words <span id="count1">0</span></p>
<p>Characters <span id="count2">0</span></p>
<textarea rows="5" id="mycounter">This is default text</textarea>

  • Related