Javascript, save the initial values of the variables

Asked

Viewed 1,963 times

0

Guys, I’m making a little code in JS, in it I need to save the initial values of my html. I have a paragraph field(<p>) that starts in a way, I wanted to save the initial state of this paragraph so I would always compare the current state with the initial state, but for some reason this is not working.

The HTML code line:

<p class="cont" id="res">A soma dos primeiros <input id="cont" type="number" name="num" min="0" max="100000000"> multiplos de <input id="mul1" type="number" name="num" min="1" max="1000"> e <input id="mul2" type="number" name="num" min="1" max="1000"> é: </p>

JS Code:

window.onload = function() {
    //quando a janela carrega eu salvo o estado inicial do <p>
    var pad = document.getElementById("res");
    //funcao q faz o calculo
    document.getElementById("calcmult").onclick = function () {

        var contador = document.getElementById("cont").value;
        var num1 = document.getElementById("mul1").value;
        var num2 = document.getElementById("mul2").value;
        var i=0;
        var x=0;
        var y=0;
        while(i<=contador){
            if(x%num1 == 0 && x%num2 == 0){
                y = y + x;
                i++;
            }
            x++;
        }
        //defino que x é igual ao paragrafo
        x = document.getElementById("res");
        //o html de x é igual ao valor inicial do paragrafo + y que é o valor
        x.innerHTML = pad.innerHTML + y;
        //zero os valores que estavam nos campos
        document.getElementById("cont").value = '';
        document.getElementById("mul1").value = '';
        document.getElementById("mul2").value = '';
    }
}

For some reason it saves the initial state all the time, making the initial state change and not making the effect I want. Now when I calculate it, in the second run, concatenate the response values instead of simply comparing with the initial state, which has no answer yet, and give only one value.

My ultimate goal is, for example, I have the following paragraph:

Type the first number to add the value ________, type the second ______, the sum is: outworking.

I want the result to be in the same paragraph, I know it is easier to create another paragraph, but I wanted to do the same for reasons of challenge. Does anyone know how to solve my problem? Thank you

Obs: These images should help you better understand the problem:

Initial State:

Estado Inicial

After performing a calculation:

Depois de realizar um calculo

After the second calculation, current state of the code:

Depois do segundo calculo, estado atual

Second calculation, final goal:

Segundo calculo objetivo

3 answers

2


It’s because you’re messing with objects.

The line

var pad = document.getElementById("res");

Creates no other object, it creates a reference, in the variable pad for the object that can be accessed through document.getElementById("res").

To save a copy of the object, use the function cloneNode, in this way:

var pad = document.getElementById("res").cloneNode(true);

The parameter is to copy all child elements, if they exist. This function also copies the id, so if you add it to the same document, it is recommended to change the id.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

  • Aeee, it worked out! Thank you very much, in the courses I did (online) none showed this cloneNode, but thanks anyway! : 3

0

Is that it? Note the Numer to String cast of variable y. Moreover I give a replace in element p whenever I need to update it:

window.onload = function() {
  var pad = document.getElementById("res");
  document.getElementById("calcmult").onclick = function() {

    var contador = document.getElementById("cont").value;
    var num1 = document.getElementById("mul1").value;
    var num2 = document.getElementById("mul2").value;
    
    var i = 0;
    var x = 0;
    var y = 0;

    while (i <= contador && contador && num1 && num2) {
      if (x % num1 == 0 && x % num2 == 0) {
        y = y + x;
        i++;
      }
      x++;
    }


    var x = document.createElement("p");
    x.innerHTML = pad.innerHTML + " " + String(y);
    document.getElementsByTagName("body")[0].replaceChild(x, pad);
    pad = x;

    //zero os valores que estavam nos campos
    document.getElementById("cont").value = '';
    document.getElementById("mul1").value = '';
    document.getElementById("mul2").value = '';
  }
}
<p class="cont" id="res">A soma dos primeiros
  <input id="cont" type="number" name="num" min="0" max="100000000">multiplos de
  <input id="mul1" type="number" name="num" min="1" max="1000">e
  <input id="mul2" type="number" name="num" min="1" max="1000">é:</p>
<input type="button" value="Calcular" id="calcmult">

  • No, this part ends up doing what my code already does =/

0

Simple, because you are always reading the current html using pad.innerHTML. You’d have to keep the value of html at the beginning, not the reference of the:

var pad = document.getElementById("res").innerHTML;

Fiddle

But I don’t recommend this practice. Why not use an element at the end of the message to display the value? Example:

... é: <span id="resultado"></span>

And then at the end of the script:

x = document.getElementById("resultado").innerText = y;

Fiddle

  • The version of Inner gave Nan e.e, but I know q could do it by creating a span, but I really wanted to try it in the same html. hm

  • @Alexandregomes must have missed the y.toString(); at the time of concatenating. Take a look at line 22 of the first demo.

Browser other questions tagged

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