Display Variable in HTML - javascript

Okay, I've seen a ton of variants of this question posted with no answer that seems to apply to my situation.
In the most direct terms possible, I have a function that calculates a number variable named score. That variable's value is arbitrary.
Is it possible for me to, in a code section, have that single variable be sourced into the html from an externally sourced JS file?
<div>
Thank you for completing my quiz!<br/>
Your score is:<br/>
(The variable would go here)<br/>
Please try again sometime!
</div>
I would want it to just display a number there, that changes based on the value of the score variable. is that possible?

HTML can't pull values from JavaScript. You need to write JavaScript to manipulate the DOM (e.g. with document.getElementById and document.createTextNode and element.replaceChild) whenever the data gets updated.
Frameworks such as React or Angular might help you achieve this.

Is it possible for me to, in a code section, have that single variable be sourced into the html from an externally sourced JS file?
If you want to get a the value of a variable that exists in an external location you can do this:
Let's say you have a file named "file.js" that contains:
var helloworld = "This is a string";
If you want to access that variable that is is global scope from your HTML code, add the script tag:
<script type="text/javascript" src="..url_to_the_file.."></script>
inside the <head> tags.
And then in your javascript that should be below that, you can type:
<script>
document.write(helloworld);
</script>
And it will print the value of the variable helloworld. I guess this is what you wanted to do, because you are printing the value of a javascript variable that exists in an external location

Related

How to read a variable declared in a html file inline script to another html inline script

I have two html files e.g. abc.html & rst.html.
abc.html has inline script having a variable x declared inside it with some value.
Now I want to access the x value inside rst.html file's inline script.
Could you please let me know if this is possible.
You can't.
JavaScript does not let you access other tabs (to some extend, you may be able to access <iframes>s which could be in a separate window, but that's it and newer browsers generally prevent such accesses).
While in your browser, you have access to one set of global variables that are in that one window. Anything else is not accessible for security reasons.
The only way you would be able to do that is by using AJAX to read the second file and then search for the variable and grab the value. Good luck doing that...
The simplest for you will be to create a file, say x.js, and load that in both HTML pages. Now you will have access to all the data found in x.js.

Nodered+external html with JavaScript function

I have an external report.html file which contain also JavaScript.
This JavaScript has a lot of variables which contain a lot of values. (Mb in plain text)
At the end is taken and render to the nice table. But I need take this variables out from the report.html to the Node-red and process them there.
I tried to load the file and print it out by but it did not do the JavaScript function inside.
Do I have somehow read the variable as an variable in node-red?
Of course I could do the parser and process through whole document and parse it manually but it is tuns of work in case it is possible to just load it somehow.
Given that your html is already loaded as string in msg.payload and your javascript code is bounded by <script> and </script> tags, you can first parse your html by:
var jsCode = msg.payload.split("<script>").pop().split("</script>")[0];
And then to run the code represented in jsCode string use eval() function:
eval(jsCode);
Your environment will act as it was written in editor and executed by you, so you should have access to all vars and functions declared in the inline js code.
Disclaimer
Actually it is not safe to use eval() SEE WHY, but for your case maybe it's the best solution.

ASP.NET core | How to use same variable in HTML file and Javascript file?

So I'm working on my first webapp in visual studio and I'm having a problem.
In my HTML file I want to declare a variable that I can use in my javascript file, but I do not know how.
I know the basics of html, but I don't know much javascript (but I need to use it).
Is there a way I can declare a variable in my html script and use the same variable with the same given value in an other javascript file
So the variable needs to be used in API.js and registreerPagina.csHTML
Thanks in advance for helping me!!
The simplest way is just to put a tag in your HTML. This will just inject the javascript into your page.
<script>var msg = "Hello world";</script>
But because Javascript is a script, you need to be sure that your tag is rendered before your javascript file tries to use it. That's a bit more of a complex subject, but this is the basic idea if you just want to declare a variable.
Regardless of the server-side structure, the resulting client-side is ultimately just one "page" in the browser and any JavaScript on or referenced by that page is executed by the browser. So in that page you can do something like this:
<script type="text/javascript">
var x = 'some value';
</script>
<script type="text/javascript" src="someFile.js"></script>
If there's code in someFile.js which references a window-level variable called x then that variable will at that time have the value 'some value'. All of the JavaScript loaded, whether on the page or references in a separate file, will be executed in the order it's loaded and all under the same window context.
In structures such as ASP.NET this can be useful when a value is dynamic in the view and needs to be used in the JavaScript, which sounds like the situation you're experiencing. Suppose you design your JavaScript file such that it gets loaded and then needs to be invoked with some injected values. You can have something like this:
<script type="text/javascript" src="someFile.js"></script>
<!-- lots of page content, then at the bottom... -->
<script type="text/javascript">
var x = '#someServerSideValue';
invokeJS(x);
</script>
In this case there could be lots of code within someFile.js, but it's all just defined and not actually executed yet. Its execution is wrapped in a function to be invoked when the page finishes loading. (In this case that function is called invokeJS.) That function expects a parameter (or multiple parameters) to provide it with values needed by that code, much like dependency injection.
So, there are a couple of ways you could approach this. The first method would be to create an API controller in your application and call the endpoint to return your value/values:
// Assuming you have referenced jQuery
$(function() {
$.getJSON("/api/schweetvariable", function(data) {
localVar = data;
});
});
The other way would be to generate the JS file from the server side via a httphandler or similar. Honestly, I'd go the API route as its pretty straightforward and easy to implement and maintain.
There are a few other ways you could achieve this: SignalR with a persistent connection or inline your API.js logic if that's an option.

What is the best way to pass a list to javascript with Jinja2 without mixing the html and js code?

I am using Jinja2 for making templates, and from what I have seen in other questions, I can pass a list to the template using the {{x}} notation. My problem is, wouldn't that mean that I would have Javascript code in the HTML template?
From what I understand it is better to separate the scripts from the HTML, and just call the scripts before closing the body tag. If I do something like what I wrote first, that wouldn't be the case, as seen in the example below.
<body>
(Other page elements)
<script type="text/javascript">
function test_func(data) {
console.log(data);
}
test_func({{ data|safe }}) <-- MyList
</script>
</body>
In this case I would have some javascript in my html template, which as I understand is not optimal. How can I solve this?
The data could be loaded from an endpoint through AJAX or stored in your DOM.
Either using a tag and the window object if you expect to use it in multiple places in your application and have no problems with polluting the global namespace
<script>
window.myInitData = {{{myJSdata}}};
</script>
or on a DOM element
<div data-data={{{myJSData}}}></div>
which you'd then query for
var data = document.querySelector('yo').dataset.data;
test_func(data);
Now addressing your question about "storing JavaScript code in your HTML" for sure, you would not like to embed the JavaScript like that unless you're doing tracking or loading of external scripts. However storing data in the DOM would be considered fine, normally, and the upshot of doing the storing in data attributes is that scripts loaded through your normal script tags would get access to your data by querying for it.

How to create a global variable that can be accessed from external javascript as well as asp.net website

In my website we have one common javascript where we will assign value to a variable i want to call that variable in my aspx page as well as in another javascript file can anyone let me know how to declare that kind of varibale globally .
you can write a common javascript file which will contain all the global variable(assuming they are constant and they wont change).
if you have the variable value as non constant, there is noway that you can put it in a javascript file, instead you can use the local storage, cookies to store the information and use it across your javascript files.
the life time of a javascript variable is limited to the page, you navigate to other page its lost.
If you do not expect any page to assign new values in your common javascript, you can add it to the page as the first header script :
<script type="text/javascript" src="script/common.js"></script>
If you want to assign new values and reuse them, it is possible if you let ASP.Net generate your javascript file by passing a query string to the next page's URL, then in that page's script tag. Let's assume that your common variable is called "myGlobalVar". Supposing that "common_js.aspx" dynamically generates your variable definition, you can have something like this :
(URL : www.mysite.com/products.aspx?myGlobalVar=3)
<script type="text/javascript" src="script/common_js.aspx?myGlobalVar=3"></script>
This will keep track of your new js value whenever an update has to be made.
But if so, you may likely want to use a cleaner way to achieve what you want, for example : using the context manager instead of common js vars.

Categories