If you.mean from a different web page: they are separate web pages. When you open the new page it doesn’t know anything about the previous page. JavaScript executes in the context of a web page, it’s a script attached to that page.
If you put everything on the same page, then you don’t have the issue you’re having: if you use JS to handle the form submission on that page and don’t navigate to a new page then it will work: user types something in, you show the result (using JS) when they click the button to submit their answer. (Edit: this is basically what libraries like React provide, they let you build an application on a single HTML page using JS, but using one would add an incredible level of complexity for the very simple thing you’re trying to do)
If you want to store a value between web pages, you need to put it somewhere. Browsers provide various simple utilities for doing this: Local Storage would be the easiest here. You access it via JavaScript. On the first page you would store the value in localStorage, on the next page you would read localStorage to get the value out
If you mean just in a different file, referenced on the same HTML page, and with code in the second file accessing a variable defined in the first file. Then a. you shouldn’t really do that (it gets too complicated) but b. it shouldn’t make any difference, because all the JS is evaluated in one context, so I’m not sure if you have some logic wrong somewhere else. In your case, where you’re using var
, you should just be able to define your variable at the top level in one file, and it’s in global scope, so second file can “see it”. But this is definitely the wrong way to think about it because
You aren’t deleting or adding anything to a file. The browser opens a webpage, and evaluates any JS attached to that page. That JS is just static text, it doesn’t get modified. The JavaScript code that text describes is evaluated, and will be run while that webpage exists, but once you navigate away it’s a clean slate, you start again fresh.
If this is the case, that you’re talking about two JS files but one HTML page, if you’re having issues why not just have one file with all the code in?
Edit edit:
@toasted121 this is literally what JS is for: some interactivity that can’t be provided with just HTML. What OP is asking about is kinda base level common, it’s often one of the first things people want to do when they first start playing around with HTML/JS (how do I store values that are typed in on one page then use them on another page?). What you’re talking about is incredibly complicated vs. the basic, core APIs that come with browsers. You do not need a framework for this, it is almost trivially simple with application of a few basic browser functions, this is where OP is at
@zaklina this won’t help w/r/t what OP is asking