Calculate the number of characters in the input and increase a variable by one every x characters

Currently, I am incorporating AngularJS into a new project and faced with the task of counting the length of a textarea. Adding up the total number of "pages" in the messaging app every 160 characters while decreasing if text is removed.

Obtaining the length of the textarea using Angular is straightforward:

<textarea ng-model="message" class="form-control" name="message" id="message" cols="30" rows="2"></textarea>
<span class="help-block"><strong>Characters</strong>: <% message.length > 0 ? message.length : 0 %></span>

I believe that handling the logic to figure out the number of pages should be done in my Javascript code, but I'm struggling to connect the ng-model to my script. Any guidance on this matter would be greatly appreciated.

Answer №1

Instead of using ng-change, you can directly manipulate the DOM:

<textarea ng-model="message" class="form-control" name="message" id="message" cols="30" rows="2"></textarea>
<span class="help-block"><strong>Characters</strong>: {{ (message.length - message.length % 160) / 160 + 1 }}</span>

Check out the code on jsFiddle: http://jsfiddle.net/EEMd3/

update

If you want to factor in additional details, simply include them in the calculation:

{{ (message.length - message.length % 160 + user.name + agency.nickname + ...) / 160 + 1 }}

Answer №2

Collaborating with Evandro Silva and incorporating ng-change:

$scope.updatePages = function(length)
        {
            $scope.totalPages = Math.round(length / 160) + 1;
        }

<textarea ng-model="content" class="form-control" ng-change="updatePages(content.length)" name="content" id="content" cols="30" rows="2"></textarea>
<span class="help-block"><strong>Character Count</strong>: <% content.length > 0 ? content.length : 0 %></span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve the type of a computed keyof T as a generic type within TypeScript

I am working with two different interfaces: interface PersonRequirements{ user:string, password:string, id:number } export interface Requirement<R> { name: keyof R & string, save: () => any,/* I want this return type to be ...

The function Firebase.database() is unavailable in the Sails Service

I have developed a service named Firebase.js, and I am attempting to utilize it from my Controllers by using Firebase.database. However, I am encountering an error stating that Firebase.database() is not a function services/Firebase.js var admin = requir ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

React Select feature fails to show suggestions after asynchronous debounced call

I am currently utilizing react-select to load results from an API while debouncing queries using lodash.debounce: import React, {useState} from 'react'; import AsyncSelect from 'react-select/lib/Async'; import debounce from 'lodas ...

Retrieving information from MongoDB

Currently, I am working on retrieving data from MongoDB and passing it to my Express server to eventually display it in my HTML using Angular. The retrieval process is successful when there is only one record in the database. However, if multiple records a ...

What is the best way to automatically scroll to the bottom of a modal after making a request and

I've been faced with a challenge regarding an online chat widget. My goal is to automatically scroll the widget down to display the latest message when a specific chat is opened. Despite using an async function, I encountered difficulties in achieving ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

Add video details to the database using the API

I currently have my own database of YouTube videos which includes the video IDs found in the video links. My goal is to find a way to insert both the title and description of these videos into the database using the YouTube API and MySQL. Although I have ...

Using the `find()` method in a loop of Mongoose iterate

Searching for documents based on conditions stored in an array can be quite useful. Take this example: subscriptions=[ {teacher: 'john', student:'david' ,course:'math'}, {teacher: 'john', student:'david' , ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Choosing the Angular5 model

I'm currently working with an Angular5 project that has a <select> element bound to an array of customers. Here's the code snippet: <select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name=" ...

Using VueJS for reactive binding效果

I am attempting to assign a class using the following syntax: :class="{active: favs.medium_title.fontWeight === 'bold'}" However, the fontWeight attribute is not yet defined when the component loads. This is an excerpt from my object: favs: { ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

Determining the latest date within a multi-faceted attribute

Incorporating Angular $http, I have successfully retrieved a model from a database. This model consists of a Forum object with various Topics, each containing multiple Posts. My current task involves creating a grid to display |Topic Description|Count of ...

When working with ES6 modules, the value of `this` and $(this) can be undefined

I attempted to integrate the toggleImage functionality into a gallery and referenced this thread along with the code provided in one of the responses. However, upon doing so, I encountered the error message Uncaught TypeError: Cannot read property 'at ...

How to retrieve data obtained from parsing readline and fs in node.js beyond the scope of the callback function

This specific question diverges from the one mentioned with an existing answer. It pertains to a snippet of code taken from node.js documentation involving the use of fs and readfile, with a focus on detecting an end-of-file flag, which appears to be the r ...