Insert percentage in progress bar (JAVASCRIPT)

Asked

Viewed 1,039 times

0

I made a progress bar with bootstrap. Then each time something is filled in the table a certain percentage more is inserted in the bar. The data that is entered into the table comes from an API, so it does this automatically. I did it as follows:

function Progresso(){
  var progressTest = document.querySelector('.info-nome');

  var teste = progressTest.textContent || progressTest.innerText;

  var cont = teste.length;

  if (cont > 0) {
    var Porc = document.getElementById('progresso_Id').style.width = "5%";
  }
}

If the class that comes from the api that contains the name is filled in, that is, it is more than 0, it will insert 5% in the progress bar. But unfortunately it doesn’t work as I want it to. Another example of the rest of my code:

function Prog() {

  var progressTest = document.querySelector('.info-cpf');

  var teste = progressTest.textContent || progressTest.innerText;

  var cont = teste.length;

  if (cont > 0) {
    var Porc = document.getElementById('progresso_Id').style.width = "10%";
  }
}

That is, it is not adding +5%, but 10%, so if the name is not inserted and Cpf yes, it already goes to 10%

How do I insert +5% and no longer change the width of the progress bar? The progress bar is by bootstrap

    <div class="container conteudo">
  <div class="row nospace">

            <div class="progress">
          <div class="progress-bar progress-bar-danger active progress-bar-striped progresso" id="progresso_Id" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width:0%">
            <span class="sr-only">0%</span>
          </div>
            </div>

 </div>
</div>

And you can do this in pure javascript? If possible, I would also like to know how put to show how much percent already has in the bar for the user to see

API:

    var endereco = `http://api`;

$.ajax({
    url: endereco,
    crossDomain: true,
    complete: function(res){
        var meuJSON = JSON.parse(res.responseText);

        var a = [meuJSON];

        a.forEach(function(element) {
            console.log(element);
            for (var i = 0; i < 1; i++) {
              element[i]
              var adiciona = element;

AdicionaNome(adiciona[1]);
AdicionaCPF(adiciona[1]);
AdicionaProduto(adiciona[1]);
AdicionaCidade(adiciona[1]);
AdicionaCodigoProduto(adiciona[1]);
AdicionaCodigoCliente(adiciona[1]);
AdicionaStatus(adiciona[1]);
AdicionaEntPrevista(adiciona[1]);
AdicionaEntregaProgramada(adiciona[1]);
  • The variable teste.length returns the values from 0-100? You can create a variable to store the value and then add up to 5 + 5.

  • test.length returns the amount of characters you have in the given class

  • @maria puts the html inputs

  • @Juliohenrique Has no html input

  • The API data you mentioned comes in the form of JSON or itself API render HTML? I couldn’t understand

  • @Matheuscuba I format it in JSON, then create a td by js to insert them. I will put in the question the way q mexo in the API

Show 1 more comment

1 answer

1

First, it is not a good idea to leave the value to be added fixed in the Code. You can simply count the fields and divide by 100, giving you the amount in % equivalent.

Then you can create an Array with the fields you need to account for (the name of the classes you use in .info-*) and call the function I put in the Snippet

All in pure Javascript

//Campos que deseja contabilizar
var listaCampos = ["cpf", "nome", "idade", "endereco"];

//Elemento da Barra de Progresso
var barraProgresso = document.getElementById("barra");
function Progresso(){
   var total = 0;
   
   //% equivalente a cada campo
   var count = 100/(listaCampos.length);
   for(var i in listaCampos){
      var campo = listaCampos[i]; 
      
      //Verifica se campo Existe
      var campoEncontrado = document.querySelector('.info-' + campo);    
      if(campoEncontrado){ 
          //Soma Porcentagem equivalente ao Total
          total += count;
      }
   }
   
   //Seta Propriedades da Barra de Progresso
   barraProgresso.style.width = total + "%";
   barraProgresso.innerHTML = total + "%";
}


//Funções apenas para Demonstração do Código

var pessoa = { nome: "João Silva", cpf: "123.123.123-00", endereco : "Visconde de Pelotas", idade: 32 };
var resultado = document.getElementById("resultado");

function InserirCampo(prop){
    var elemento = document.createElement('span');
    elemento.className = "info-"+prop;
    elemento.innerHTML = pessoa[prop];
    resultado.appendChild(elemento);
    Progresso();
}
span{
   margin: 10px;
}

.progress{
  margin-top: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button onclick="InserirCampo('nome')">Inserir Nome</button>
<button onclick="InserirCampo('cpf')">Inserir CPF</button>
<button onclick="InserirCampo('endereco')">Inserir Endereço</button>
<button onclick="InserirCampo('idade')">Inserir Idade</button>

<div id="resultado"></div>


<div class="progress">
  <div class="progress-bar progress-bar-striped active" role="progressbar" id="barra"
  aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:0">
    0%
  </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.