Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cshelswell's avatar

Count Characters in input field on Page Load

There's probably a really simple answer to this but I'm just starting out with Vue and can't seem to find any info on it.

I'm just building a really simple character counter to show how many characters are in an input field. I've got it work to count as the user types

<label for="title">SEO Description - Character Count: @{{ seo_description_characters }}
                        <input tabindex="4" class="" name="seo_description" type="text" value="{{ $product->seo_description }}" maxlength="156" v-on:keyup="seo_description_characters++" id="seo-description" />
                    </label>

<script>
new Vue({
    el: "#vue-app",
    data: {
        seo_description_characters : 0
    }
});
</script>

That all works nicely to increment the characters as a user types. The thing I've not got is how to set the seo_description_characters if there's already text in there. I could just use a bit of jquery

$('#seo-description').val().length;

But i'm assuming there's a more vue way to do it?

Thanks

0 likes
4 replies
cshelswell's avatar

Ok so as it turns out I've a bit more to learn. Using keyup is a pretty terrible way to count it as it still considers a delete to be a keyup.

Back to the drawing board :)

richpeers's avatar

Have a look at computed properties https://vuejs.org/guide/computed.html and Form Input Bindings https://vuejs.org/guide/forms.html something like:

<label for="seo-description">SEO Description - Character Count: @{{ seoDescriptionLength }}</label>
    <input tabindex="4" class="" name="seo-description" type="text" value="{{ $product->seoDescription }}" maxlength="156" 
           v-model="seoDescription" />


<script>
    new Vue({
        el: "#vue-app",
        data: {
            seoDescription: ''
        },
        computed: {
            seoDescriptionLength: function () {
                return this.seoDescription.length;
            }
        }
    });
</script>
davestewart's avatar
Level 11

All you need is to bind the input to a model, then use that to get your length:

<label for="title">SEO Description - Character Count: @{{ seo_description.length }}
    <input 
        v-model="seo_description"
        value="{{ $product->seo_description }}" 
        maxlength="156" 
        />
</label>

<script>
new Vue({
    el: "#vue-app",
    data: {
        seo_description : ''
    }
});
</script>

2 likes
cshelswell's avatar

@data7of9 & @davestewart

I'll check out the computed properties but for now @davestewart yours works great thanks! I thought there'd be a really simple way to do it, certainly way less coding that jQuery to do it.

Thanks!

Please or to participate in this conversation.