0

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>
        
 

1
  • You need to move document.getElementById("x2").innerHTML = "Your car is " + car; inside save_car() if you want it to update on click, which also negates the need for a global variable as you can just set it to input.value as well. Commented Oct 28, 2020 at 22:51

1 Answer 1

1

The main issue is that you were setting "x2" outside of your save function.

I made a few other notes/comments in the code below.

// var car;  <-- you didn't need this global variable

function save_car() {
    let car = document.getElementById("car-text").value;
    let innerString = "Your car is " + car; // <-- we're going to reuse this, so store in variable
    document.getElementById("x1").innerHTML = innerString;
    document.getElementById("x2").innerHTML = innerString; //moved inside save_car() function
}

// save_car(); <-- you don't need this either
  <input id="car-text" type="text">
  <button onclick="save_car()">Save</button>
   
  <p id="x1"></p>
  <p id="x2"></p>
        
 

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much ! And how could I acces the innerString outside the function ?
You could (1) declare it outside and set it within the function similar to how you were doing, or (2) fetch it again where it's needed with document.getElementById("car-text").value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.