user3718511
user3718511

Reputation: 335

How to properly implement the global variable in javaScript?

I am having a difficulty in displaying the value of totalPrice into my console. I am just getting 0 in my console but I want to get the actual value of each radio button. Can anyone help me please?

html

<lable>Radio1</lable>
    <input type="radio" id="radio1" name="pay" class="myPay"  value="2"/>
    <label>Radio2</label>
    <input type="radio" id="radio2" name="pay" class="myPay"  value="3" />

js code

var totalPrice = 0;
var radio = document.querySelectorAll(".myPay");
radio.forEach(check => {
  check.addEventListener('click', function(e) {
    totalPrice = e.target.value;
  });
});
console.log(totalPrice);

Upvotes: 0

Views: 66

Answers (3)

Dan Mullin
Dan Mullin

Reputation: 4435

Move your logging into your event listener

var totalPrice = 0;
var radio = document.getElementsByName("pay");
radio.forEach(check => {
    check.addEventListener('click',function(e){
        totalPrice = e.target.value;
        console.log(totalPrice);
    });
});

Upvotes: 1

Nick
Nick

Reputation: 1629

You can put the global variable in un IIFE like this you can prevent those problems of global variables like unexpected name collision. However to use a global variable you can simply declare with the var keyword outside from each function.

(function(){
let totalPrice=0;
    var radio = document.querySelectorAll(".myPay");
     radio.forEach(check=>{
    check.addEventListener('click',function(e){
             
        totalPrice = e.target.value;
    });
});

document.getElementById("price").addEventListener("click",(event)=>{
  document.getElementById("display").value = totalPrice;
});
})();
<lable>Radio1</lable>
    <input type="radio" id="radio1" name="pay" class="myPay"  value="2"/>
    <label>Radio2</label>
    <input type="radio" id="radio2" name="pay" class="myPay"  value="3" />
    
    <div>
    <input type="text" id="display" value="0">
    <button id="price">Totale price</button>
    </div>

Upvotes: 1

jhrmdk
jhrmdk

Reputation: 642

You must console.log(totalPrice) right under totalPrice = e.taget.value;

Upvotes: 1

Related Questions