Instructions for filling a progress bar according to the quantity of characters typed

I'm attempting to create an input box with a bottom div that acts as a progress bar, indicating when enough characters have been typed.

I've been struggling to get the animation working, even though I initially thought it would be a simple task for this project.

If you could review my code and point out any errors, I would greatly appreciate it. Thank you!

<div id='cntnr'>
  <div id='inptDiv'>
    <input id='inpt1'>
    <div id='prgInd'></div>
  </div>
</div> 

var main = function() {
  var inptAmnt = document.getElementById('inpt1').value;
  if(inptAmnt.length === 1) {
    $('#prgInd').css('width', 25);
  }
}

$(document).ready(main);

I attempted the following code first, but it didn't work as expected:

var main = function() {
  var inptAmnt = document.getElementById('inpt1').value;
  if(inptAmnt.length === 1) {
    $('#prgInd').animate({
      width:25
    },200 )
  }
}

$(document).ready(main);

JSFiddle: https://jsfiddle.net/qcsb53ha/

Answer №1

To track the change, keyup, and paste events of an input field with jQuery, you can follow these steps.

Determine a percentage based on your desired input length and use this percentage to adjust the width of a progress bar accordingly.

If the calculated "percentage" exceeds 100, simply set it back to 100. The jQuery script for achieving this is provided below:

var desiredLength = 4; // Be serious...

// Listen for change, keyup & paste events
$('#text-box').on('change keyup paste', function() {
    // Get the length of the input value
    var textLength = $('#text-box').val().length;

    // Calculate the percentage
    var percent = (textLength / desiredLength) * 100;
    // Ensure the percentage does not exceed 100
    if (percent > 100) {
      percent = 100;
    }

    // Animate the width of the progress bar based on the percentage
    $('.progress-bar').animate({
      width: percent + '%'
    }, 200)
});

Check out the functional JSFiddle demo here: https://jsfiddle.net/jqbka5j8/1/

The code includes instructions for both setting and animating the width of the progress bar. You can toggle between them to test as needed.

Trust this explanation is beneficial!

Answer №2

Avoid using Javascript and opt for pure CSS along with the use of Content Editable to achieve the desired result:

Sample HTML code snippet:

<div>
    <span contenteditable="true">sdfsd</span>
</div>

CSS styling for the elements:

span 
{
    border: solid 1px black;
}
div 
{
    max-width: 200px;   
}

Check out this JsFiddle example for a live demonstration.

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

The dropdown div does not activate when the image is clicked

When the image in the simple dropdown is clicked, it fails to activate the dropdown feature. This issue was encountered while working on a Shopify project, making it challenging to troubleshoot. To demonstrate the problem, I have re-created the scenario i ...

Will the browser refuse input that is not a number if the <input type='number'...> tag is utilized?

If I set the input type to 'number', will the browser automatically verify and reject any non-numeric inputs in this field before submitting the form? ...

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

There seems to be an issue with the implementation of the border-radius-top-left property in

I'm having trouble getting my button to curve at specific corners in my NativeScript App. Below is the CSS code I've used: border-bottom-left-radius: 10; border-top-left-radius: 10; border-top-right-radius: 0; border-bottom-right-radius: 0; I h ...

Create a function that outputs an array containing objects as its elements

Struggling with this one, I've hit my head against all corners but something seems to be missing. Details I'm working on a small JavaScript page that retrieves a Facebook photo ID, calculates the total number of people who shared it, identifies ...

The footer fails to remain at the bottom of the page when there is limited content available

Despite searching extensively on Google, I have not been able to find a solution to this frequently asked question. My challenge is to consistently position the footer at the bottom of the page, even when there is minimal content present. Below is an exce ...

Creating a div that is positioned below an input form when it is focused can be achieved using

I am aiming to achieve the following: https://i.sstatic.net/AxIXs.png My goal is to generate a new div positioned directly below the input form that has been selected (each of the 3 input fields displayed will have a distinct div underneath). The selectio ...

React Native: Unexpected Challenge in State Updates

Below is the code I am currently using: makeRemoteRequest = () => { let items = []; models.forEach(element => { //models contains an array of different models this.pushReports(element, items); }); console.log("The item ar ...

Is it possible to use Sass properties as arguments for my function?

My attempt to use SASS properties as arguments for my function seems to be failing miserably. Is there a way I can achieve this, or is there a better solution to what I'm trying to do? I am looking to dynamically change the values of variables based ...

NestJS WebSocketGateway fails to initialize due to a technical glitch

After following the instructions in the NestJS documentation, I set up the websockets gateway within the AppModule. The server is starting without any issues, and I'm able to serve static assets via HTTP successfully. However, I'm facing difficul ...

Visual content may be unavailable during program execution

When attempting to apply an image in the background of an HTML tag using CSS, I am encountering an issue where the image is not visible during runtime, even though it appears during design time. Additionally, I am curious as to why the full path needs to b ...

Setting up conditional select options in Angular

I need to create a select list with specific options based on the data in an object. For instance, if the data property is 0, I want to display an option as 0 with the ability to switch to 1, and vice versa. However, when rendered in HTML, no option value ...

Tips for avoiding the security risk of "A potentially hazardous Request.Form" in requests

After integrating a FreeTextBox control into my webpage, users can input HTML tags. However, upon submitting to the server, I encounter the following error: A potentially dangerous Request.Form value was detected from the client (GestisciPagine1_txtTest ...

Troubleshooting problems with an Angular controller

I am currently working on developing a basic app that retrieves data from MongoDB. However, I encountered an error in the console: Uncaught TypeError: Cannot read property 'controller' of undefined at model.js:8 'use strict'; var mi ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

Exploring the bug in Vue.js and Webpack 5 Federation with TypeScript

Encountering an issue with a new webpack 5 module Federation and TypeScript. I have two separate VueJS applications, both written in VueJS 3. The problem seems to be related to the webpack configuration and the ts-loader, which requires the appendTsSuffixT ...

Expanding container width as input fields are dynamically added

I have a tab with a title. I would like it to become editable when the user double clicks on it. Currently, I hide the div containing the title and replace it by adding an input element dynamically. However, when I add the input element dynamically, the si ...

Enhance your user interface with Bootstrap Multi-select by incorporating images alongside checkboxes

First off, you can find the working example here I'm attempting to insert an image after each checkbox for the Bootstrap multi-select plugin. I have tried a couple of methods so far: Adding images directly in each option, but the plugin removes all ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...

Sort activities according to the preferences of the user

This is the concept behind my current design. Click here to view the design When making a GET request, I retrieve data from a MongoDB database and display it on the view. Now, I aim to implement a filter functionality based on user input through a form. ...