I am quite new to Javascript and I have veeery simple program that takes value from HTML input and then it should reassign variable car. However, the second x2 seems not to recognize the value, only the x1. I have read some articles and a few programmers do not recommend the usage of global variables, if it is not needed.I would also like to access my variables outside the function Thank you in advance for answering this stupidly simple code.
var car;
function save_car() {
car = document.getElementById("car-text").value;
document.getElementById("x1").innerHTML = "Your car is" + car;
}
save_car();
document.getElementById("x2").innerHTML = "Your car is " + car;
<input id="car-text" type="text">
<button onclick="save_car()">Save</button>
<p id="x1"></p>
<p id="x2"></p>
document.getElementById("x2").innerHTML = "Your car is " + car;insidesave_car()if you want it to update on click, which also negates the need for a global variable as you can just set it toinput.valueas well.