How to count commas in a text field and show how many commas in another text field

So i have this code, and i put in names in the word_count text field separated by comma:

<input type="text" id="word_count" name="Workers name">
<input type="text" id="word_counter" name="Workers" class="word_counter">

<script>
    $(document).ready(function(){
        $('input#word_count').on('keypress',function(){
           var charCount = $(this).val().split(/[\.,\?]+/).length;
            $(".word_counter").text(charCount);
        });
    });
</script>

But i cant see the amout in the word_counter text field, but if i check in Firefox console i can see that the amout changes: 2
here i have typed in the word_count text field: name 1, name 2.
And also the input text fields are in a mail form.

You want to change the value of the input element, so it’s

$(".word_counter").val(charCount);
//                 ===

There’s no text content.

Ohh. man. So simple. Thank you. Another thing, is it possibe to make this work when pasting in names?, like:
Name 1, Name 2, Name3

Also if i erase all the names the numbers are still there i would like this start whit 0 when you enter page and if i erase the names return to 0.

Thank you.

You can bind the function to the keyup event, so that it will get triggered after pasting, not before.

The reason that there’s never a 0 is that splitting an empty string will result in an array containing exactly that empty string [""]. The length of this array is still 1. So you could add a conditional like:

var charCount = $(this).val() === "" ? 0 : $(this).val().split(/[\.,\?]+/).length;

If you want to have 0 as an initial value, simply add it to the input element:

<input type="text" id="word_counter" name="Workers" class="word_counter" value="0">

Thank you this helps alot, it works with pasting the names if i use CTRL+V but it does not work if paste using the mouse. Is there also a way of doing this?

Thank you.

Regards

//Patrik.

You could do the same on mouseup. For a list of all jQuery events see, well, the API. Multiple events can be attached with on(event1 event2 ... eventn, function).

Thank You so much for your help.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.