Home > Back-end >  how can i make this script show the value of the var "per" based on the new value of the v
how can i make this script show the value of the var "per" based on the new value of the v

Time:12-25

    var a =  0 ;
    const six = 6.6666;
            
    var per = a * six;

    $(".mychoice").click(function () {
        (a  );
    });

    $(".show").click(function () {
        $("#ss").text( per );
    });

what i want is to show up the result of the variable per i tried to show the value of the variable a and it works it shows the number of times i clicked on the button with the class my choice so tried to put the value of the var a into math i created a variabl per ... per= a * 6.6666 so i tried again and it wont work the result stay 0 but if i change the value of a to 1 it shows 6.6666 so the calculation is working fine but it is not taking the value of a based on how many times i click it just take the value i gave in the script ... i would me gratfull thanks ..

CodePudding user response:

Calculations are done when you tell them to be done.

If you change the value of a in a click event, then that value doesn't travel back through time so that a is the new value back when you read it and used it to multiply six.

If you want to redo that calculation when something is clicked then you need to write that expression in that click event handler function.

CodePudding user response:

var per = a * six;

The calculation is executed and stored in the per variable as soon as the line is executed, not when you reference the per variable.

If you want to calculate the value at a later time, use an (arrow) function instead.

// define `per` as arrow function with 0 arguments
var per = () => a * six;

Then you evoke the function when you need the result:

$(".show").click(function () {
    $("#ss").text( per() );
});

In this scenario doing the calculation directly, without defining a function, might be cleaner.

$(".show").click(function () {
    $("#ss").text(a * six);
});

CodePudding user response:

var a = 0;
const six = 6.6666;
$(".mychoice").click(function () {
    (a  );
});

$(".show").click(function () {
    var per = a * six;
    $("#ss").text(per);
});
  • Related