Joshua Joshua - 3 months ago 20
CSS Question

How to fill progress bar based on number of letters typed?

I am trying to make an input box that has a div on the bottom which will act sort of a progress bar to tell you when you have enough characters typed.

I can't get this animation to work, even though I thought it would be a lot easier when I decided to try this project.

Please let me know what is wrong with my code. Thanks!

<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 also tried this code first but it didn't work either:

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

You can use jQuery to listen to the change, keyup and paste events of your text input.

Then, work out a percentage, based on your desired input length; and use this percentage to set the width of the progress bar.

If the "percentage" is above 100 - just reset it to 100 again. jQuery code is below:

var desiredLength = 4; // no jokes please...

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

    // Calculate the percentage
    var percent = (textLength / desiredLength) * 100;
    // Limit the percentage to 100.
    if (percent > 100) {
      percent = 100;
    }

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

See the working JSFiddle here : https://jsfiddle.net/jqbka5j8/1/

I've included normal code for setting the width, and the code for animating the width. You can comment/uncomment the necessary ones and test appropriately.

Hope this helps!