A guide on updating progress bar value based on user input

I have an input field and a progress bar that needs to be updated based on the input.

The task is to input a number (%) and then display that value in the progress bar upon clicking the "Apply" button (btn-primary).

Below is the HTML code provided:

<div class="form-group">
    <label for="number">Enter a Number!</label>
    <input type="text" class="form-control" id="number" min="0" max="100" required>
  </div>
   <button type="button" class="btn btn-primary">Apply</button>
   <div class="progress-wrap">
     <div class="progress-message">Your form is filled at <span class="output">___</span> %</div>  
    <progress max="100" value="0" class="progress"></progress>
    </div>

An attempt was made to write a script, but it does not function properly.

var val = document.querySelector('.form-controll').value;
var btn = document.querySelector('.btn-primary');
var progress = document.querySelector('.progress');
btn.addEventListener('click, displayData');
function displayData() {
  progress.attr('value', val);
  progress.style.background = 'green';
}

For reference, here is the link to view the codepen: https://codepen.io/ksena19/pen/QVRNep

Answer №1

I made some adjustments to your code

Feel free to view the updated version here: https://codepen.io/anon/pen/rZgLyq

Here is the modified HTML:

    <div class="form-group">
    <label for="number">Please enter a number!</label>
    <input type="text" class="form-control" id="number" min="0" max="100" required>
  </div>
  <button id="btn" type="button" class="btn btn-primary">Apply</button>
  <div class="progress-wrap">
     <div class="progress-message">Your form is filled to <span class="output">___</span> %</div>  
  <progress max="100" value="0" class="progress"></progress>
</div>

And here is the updated JavaScript:

$(document).ready(function(){ 
  $('#btn').click(function(){ 
    var val = $('#number').val();
    evaluate(val);
  });
});

function evaluate(value) {
    var progress = $(".progress"), 
        progressMessage = $(".progress-message");  

  if (value == 0) {
      progress.attr("value", "0");
      progressMessage.text("Please fill out the form.");
  }
  if (value == 1) {
      progress.attr("value", "33");
      progressMessage.text("Nice start!");
      progress.addClass('light-green');
  }
  if (value == 2) {
      progress.attr("value", "66");
      progressMessage.text("You're on a roll!");
      progress.addClass('green');
  }
  if (value == 3) {
      progress.attr("value", "100");
      progressMessage.text("Form completed!");
      progress.addClass('dark-green');
  }
}

Answer №2

This particular snippet utilizes the HTML tag. The functionality of this tag relies on the attribute value="0". If the value is set to 0, it indicates that there is no progress to display.

Here, I've provided the precise code for your reference. By entering a number in the designated textbox, the progress bar will react accordingly to the numerical input. Feel free to execute the code below:

<script type="text/javascript">
    function count(){
        var getNum = document.getElementById("number");
        document.getElementById("progress").setAttribute("value", getNum);
    }
</script>

<!-- Progress bar -->
<div class="form-group">
    <label for="number">Enter a Number!</label>
    <input type="text" class="form-control" id="number" min="0" max="100" required>
</div>
<button type="button" class="btn btn-primary" onClick="count();">Apply</button>
<div class="progress-wrap">
    <div class="progress-message">Your form is filled to <span class="output">___</span> %</div>
    <progress max="100" value="0" class="progress" id="progress"></progress>
</div>

Answer №3

I designed a demonstration page that accepts user input and displays progress upon button click. Below is the HTML code with styling and JavaScript function:

<html>
    <style>
        #myProgress {
            width: 100%;
            background-color: #ddd;
        }
        #myBar {
            width: 0%;
            height: 30px;
            background-color: #4CAF50;
            text-align: center;
            line-height: 30px;
            color: white;
        }
    </style>
    <body>
        <div id="myProgress">
            <div id="myBar">0%</div>
        </div>
        <br>
        <input type="text" class="form-control" id="number" min="0" max="100" required>
        <button type="button" onclick="change_progress()">Change Progress</button>
    </body>
</html>
<script>
    function change_progress() {
        var elem = document.getElementById("myBar");
        val = parseInt(document.getElementById("number").value);
        var width = 0;
        var id = setInterval(frame, val);
        function frame() {
            if (width >= val) {
                clearInterval(id);
            } else {
                width++; 
                elem.style.width = width + '%'; 
                elem.innerHTML = width * 1  + '%';
            }
        }  
    }
</script>

Answer №4

Your JavaScript code has been updated:

var btn = $('.btn-primary');
var progress = $('.progress');
btn.click(function(){
  var value = Number($('.form-control').val());
  progress.attr('value', progress.val() + value);
});
.progress {
    width: 20%;
    height: 20px;
    margin: 0 0 5px 0;
    background: #fff;

  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
    <label for="number">Enter a number!</label>
    <input type="text" class="form-control" id="number" min="0" max="100" required>
  </div>
   <button type="button" class="btn btn-primary">Apply</button>
   <div class="progress-wrap">
     <div class="progress-message">Your form is filled to <span class="output">___</span> %</div>  
    <progress max="100" value="0" class="progress"></progress>
    </div>

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

New to the world of web design and seeking answers as to why my style is not being applied

After diligently following the courses on CodeAcademy (I know, kind of lame but it's a start), I finally feel confident in my ability to write my own HTML and CSS code. However, when I tried to do so using Sublime Text 3 and opened my HTML file, I not ...

Finding the index of a chosen option in Angular

Attempting to retrieve the index of the selected option from a select element using Angular. The Angular (4) and Ionic 3 frameworks are being utilized. The template structure is as follows: <ion-select [(ngModel)]="obj.city"> <ion-option ...

Utilize three.js within a Google web app script - unable to incorporate the script module type for loading three.js

Looking to incorporate three.js into a Google Web Script to load 3D CAD files, I discovered that the installation instructions on threejs.org specify the script needs to be of "module" type. However, after researching for several days, it seems that Google ...

Ways to terminate session using ajax when input is empty; Notice of an undefined variable

Warning: Variable 'outputname' is undefined There is a query in the file memberSearch.php. I want to echo the $outputname variable in another PHP file inside an input tag. However, when I try to echo ($outputname) in another file, it returns an ...

How can I showcase an image from the search results using the Giphy API?

Find the GitHub link to the Giphy API here: https://github.com/Giphy/GiphyAPI. As a newcomer, I'm facing a roadblock. Currently, I am receiving random gifs from the Giphy API instead of the specific search result requested by the user. Is there a wa ...

"Encountering issues with jQuery AJAX and PHP where data values are not being

I'm having trouble retrieving the values of the data variable sent with jQuery AJAX to a php page. Any suggestions on how to resolve this issue? Check out the HTML code below: <input id="name" placeholder="Enter your name." /> <button id="s ...

Uploading files in AngularJS using Rails Paperclip

I have been working on implementing a file upload feature with AngularJS/Rails using the Paperclip gem. I was able to resolve the file input issue with a directive, but now I am facing an issue where the image data is not being sent along with other post d ...

Using LinQ filter along with jQuery tmpl in a jQuery AJAX call illustration

After implementing this script to retrieve and filter a JSON dataset containing 100,000 elements for quick user-side searches, we have encountered performance issues. The script is not running fast enough. Do you have any suggestions on how to optimize th ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

Properties of the jQuery XMLHttpRequest object in callback functions of ajax requests

If you have an ajax callback function like the one below, how can you retrieve a status/response code or other information from the 'xhr' object? function showResponse(responseText, statusText, xhr) { } Here are some attempts to retrieve inform ...

Refresh treeview in master page while loading ASP page without refreshing the entire page

Is there a way to load an aspx page without refreshing the treeview on the master page? Currently, I have a master page with a treeview where clicking on a leaf refreshes the entire page instead of just the content placeholder. Can anyone suggest a solutio ...

How to create a bottom border in several TD elements using a combination of CSS and jQuery

Check out my Website: Search Page I have written some CSS that functions well when searching by Name, but not by Specialty: .displayresult { display: block; } #fname, #lname, #splabel, #addlabel, #pnlabel { border-width: 4px; border-bottom-st ...

Achieve a dynamic transition where one slide seamlessly reveals the next using jQuery

I have been working on creating a slider that mimics the effect shown here where clicking on a button reveals different slides. I attempted to achieve this by adding 2 buttons per slide and using the following jQuery code: jQuery('#movetohappyscene& ...

Is there a way to minimize superfluous re-renders in React without resorting to the useMemo hook?

I am currently evaluating whether I should adjust my strategy for rendering components. My current approach heavily relies on using modals, which leads to unnecessary re-renders when toggling their visibility. Here is a general overview of how my componen ...

Utilize PHP to generate a table from data

I successfully created a table using information retrieved from my database, and everything is displaying as intended. However, I am facing an issue where adding a background color applies it to every row in the table. How can I add a background color wit ...

Adjustable Panel Width

Is there a way to have the width of the bottom panel expand to col-md-12 when the top panel is collapsed, and then return back to col-md-8 when the user expands the top panel again? I'm still learning, but here's what I have managed to code so f ...

Create a customizable Tree structure that includes checkboxes for each item and features drag

I am currently working on incorporating a Tree view with checkboxes and drag & drop functionality in Vue. However, I am unsure of where to begin. While I have successfully implemented checkboxes, I am struggling to figure out how to enable the feature whe ...

How to Toggle Div Visibility with AngularJS ng-show and ng-click

In order to eliminate error messages, I decided to clear the field with a button click. This approach successfully removed the error in my initial test. <div class="errorPopup" data-ng-click="runner.Name = null" data-ng-show="mainForm.name.$error.pat ...

Tips for designing a sophisticated "tag addition" feature

Currently, I am enhancing my website's news system and want to incorporate tags. My goal is to allow users to submit tags that will be added to an array (hidden field) within the form. I aim to add tags individually so they can all be included in the ...

Overlap of Bootstrap Columns Occurs When Resizing the Browser

While I recognize that this issue is common, I have extensively reviewed similar questions but could not find a solution. <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-6"> <img style="wi ...