I'm trying to get a simple javascript function to work. I know enough Javascript to think to myself, "This should work, Why isn't it working!" I'm sure we've all been there before. I have done some research to brush up on my functions and to compare my function to but to no avail, I still can't get this function to work. I'm using Javascript to try to display my name within a span element. Normally this should be easy but, for some reason it just isn't working. This is also done in a .php file and a .html file. Because i wanted to make sure it didn't matter if it was a .php file or .html file. It won't work in either. This is for a php project by the way.
Here's the code
<html>
<head>
<script>
var yourName = "Robin";
function placeName()
{
document.getElementById("myName").innerHTML = yourName;
}
</script>
</head>
<body>
<h1>PHP Basics</h1>
<h2>Hi! My Name is<span id = "myName"></span>
</body>
</html>
Like I said, This should be simple, but it won't work. I'm hoping a new set of eyes (you guys) would be able to point out my rookie mistake. If I need to explain anything in more detail please let me know. And thank you all very much.
You're not running the function. Be careful, only run the function after the span has been created or else it will not work. See this example.
<html>
<head>
<script>
var yourName = "Robin";
function placeName()
{
document.getElementById("myName").innerHTML = yourName;
}
</script>
</head>
<body>
<h1>PHP Basics</h1>
<h2>Hi! My Name is<span id = "myName"></span>
<script>
// run function
placeName();
</script>
</body>
</html>
You have made the body of the function but you haven't call the function so that it will be executed. You can do it like this
<html>
<head>
</head> <body> <h1>PHP Basics</h1> <h2>Hi! My Name is<span id = "myName"></span> </body> </html>
var
yourName = "Robin";
function placeName() {
document.getElementById
("myName").innerHTML
= yourName; }
placeName();
// it won't return undefined try it
Related
from the html below I would like to execute a script by calling his id. So that when the script id is called the display fonction execute. Any other suggestion will be appreciate as long that the script only execute when the id is called. Thank you
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//Here is where I would like to execute the script by calling his id.
//Any other suggestion to make it work will be appreciate
});
</script>
<script type="text/javascript" id="execute">
$(document).ready(function(){
display();
});
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
That's not how JavaScript works.
Once you include a <script> in DOM, it's executed. However, the script itself can define functions, which could be named and called at a later point (by their name), by any other script or element in the page, as long as they have access to the context in which you defined your function.
Example:
<script>
function myFunction() {
window.alert('I got called!');
}
</script>
<button onclick="myFunction()">Execute myFunction()</button>
So instead of using the id of the script, I'm using the name of the function.
To fully answer your question: running a script by id is not possible because all scripts are executed as soon as they are parsed by the browser (which happens in their chronological order in DOM) and there is no way of re-running them after they have already been executed.
Obviously, one could argue that you could remove the <script> tag altogether, create a new one with the same contents, which is going to be rerun when added to DOM. But, at least in theory, it's not rerunning the same <script>, it's running a different one. Another instance/<script> tag.
Needless to say, nobody does that as it's much more convoluted than to simply define a function and call that function at a later time.
Thank you for your explanation on the DOM. It help me figure out another alternative
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var result = window.prompt("Would you like the footer to be display?");
if(result == "yes"){
bodyPage1();
}
});
</script>
<script>
function bodyPage1(){
display();
}
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
I work in schools and use google forms to keep track of a number of things.
One of these forms emails people with information from the sheet that is entered.
I have managed to cobble together a good script that provides this service, however, I want it to look good.
My question is simple (or so I believe it is):
When I put in my HTML for the body of the email, how do I call the variables that I have defined earlier in the script?
Do I need to define them in the HTML or can I call them from the JavaScript?
I am not a serious coder by any means but this one has seemed to escape my ability to google it.
Any help would be appreciated.
calling a value of the variable created in javascript, outside the script.
<html>
<script>
var somevariable = "hi"; //this is the variable you create in JavaScript
window.onload = function() {
document.getElementById("blabla").innerHTML = somevariable; //here you send the value of 'somevariable' to html.
}
</script>
<body>
<input type="text" id="blabla" name="someInput"></input>
</body>
</html>
I am not too sure what your code looks like so this is only an attempt to answer what I understand so far.
In you HTML document you don't call variables, you call functions. for example when you click a button, the text would change to what your variable is by calling the onclick Event inside the button, ChangeText() will be the function for the first example:
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<button onclick="ChangeText()">Button</button> <!-- onclick event -->
<script>
var p1 = document.getElementById("p1"); //variable created
function ChangeText () {
//when you click the button this function will be called
p1.innerHTML = "Changed text on button click!";
}
</script>
</body>
</html>
You could also call on the load of the document (but this would mean that you would't see what it was before):
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<script>
var p1 = document.getElementById("p1"); //variable created
p1.innerHTML = "Changed text on page load!"; //change text on load
</script>
</body>
</html>
hope this helps.
I am working with HTML, CSS, jQuery, and JavaScript, all on one HTML page. Generally, I trying to figure out for the first time how to access information from the HTML body for use in my JavaScript code.
I want to set a variable in JavaScript equal to the string contained in the data attribute of one of my <div> elements.
Can I use document.getElementsByClassName()[] in my JavaScript to actually pull the information out of the HTML document? In examples on W3schools and elsewhere, I only see it used to change the value of some HTML element, not to actually use its input. Is there something more fundamental that I'm missing, here?
____here's my more specific code (where div.onlyOne is the only div of that class, and has the data-need attribute "string i need"):
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need")
Why will this not store "string i need" into myVar?
It works, make sure though, that you run the script after the markup or DOM load, or else the script will not find the element as it has not yet been loaded.
After in markup
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
<script type="text/javascript">
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
</script>
</body>
</html>
DOM load
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
});
</script>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
</body>
</html>
May I suggest you use document.querySelector('.onlyOne') instead in the future. With that you can narrow down the result list in a more efficient way.
Src: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
<div class="onlyOne" data-need="some text">...</div>
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
https://jsfiddle.net/howa6w1o/
since you are using jQuery, you can simplify your code to get the contents of the data-attribute: as follows:
$(document).ready(function(){
var myVar = $(".onlyOne").eq(0).data("need");
})
OK. I feel dumb! I've been trying to do something very simple and yet finding it very difficult to do or to find. All I want to do is:
have the index.html file display.
I want a separate JavaScript file that contains all of my JavaScript code. Completely separated, so I don't have any JavaScript code in my HTML file. I don't want a click event or anything fancy.
I just want the page to display Hello World! onLoad by getting it from a JavaScript function.
BTW: Seems all tutorials either put the JavaScript code in with the HTML or they want to show you how to do something fancy. I've been all over SO to no avail.
The closest I've gotten is listed below. I give up! A little help would be so appreciated.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
</head>
<body>
<script type="text/javascript"></script>
</body>
</html>
script.js:
window.onload = function() {
var result="Hello World!";
return result;
};
if you want to append to body, you can create a text node ( createTextNode() ) and then directly append that to body:
window.onload = function() {
var result = document.createTextNode("Hello World!");
document.querySelector('body').appendChild(result);
};
What you can do is print the text you want to the <body> element when the page loads. Something like this should do the trick:
window.onload = function() {
var result="Hello World!";
document.querySelector('body').innerHTML(result);
};
Or if you had a particular place on your webpage that you wanted to load this text into, you can create an element in your HTML, give it a unique id and reference it in your JavaScript:
<body>
...
<div id="myAwesomeElement"></div>
...
</body>
and in the JavaScript:
window.onload = function() {
var result="Hello World!";
document.querySelector('#myAwesomeElement').innerHTML(result);
};
In your javascript function, you can do something like this:
document.getElementById("divID").innerHTML="Hello World!";
and in your html file create a div or span or something that you want modify(in this case, the inner html content):
<body>
<div id="divID"></div>
</body>
When the function is called, it will find the dom element with the Id of "divID", and the innerHTML will be what you assign the Hello World to. You could modify other properties like css style stuff too.
If you want to grab a hold of a place where to put your file, you need to address it.
Eg.
<body>
<div id="place-for-text"></div>
</body>
And then in your script:
var elem = document.getElementById('place-for-text');
elem.innerHTML = 'Hello world.';
That is about the simplest way to do it in a way you could control some of it.
You could go more fancy and add a DOM element instead:
var elem = document.getElementById('place-for-text');
var text = document.createTextNode('Hello world');
elem.appendChild(text);
Here's a way that hasn't been shown yet.
You can remove the script tag from the head of the file since we want the js file to load up after the rest of the page. Add the script tag with the script.js source to the body.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The script.js file looks like this:
//script. js file
!function () { document.querySelector("body").innerHTML = "hello world"; } ();
The exclamation point and the following () causes the function to run automatically upon load. For more info take a look at this question: What does the exclamation mark do before the function?
EDIT
I should also point out that document.write and .innerHTML are not considered best practice. The simplest reasons are that document.write will rewrite the page and .innerHTML causes the DOM to be parsed again(performance takes a hit) - obviously with this example it doesn't really matter since it's a simple hello world page.
An alternative to document.write and .innerHTML
!function () {
var text = document.createTextNode("Hello World");
document.querySelector("body").appendChild(text);
} ();
It's a bit of a pain, but you can write a function for the process and it's no big deal! The good news is that, with the new ecmascript 6(new JavaScript) you can turn this into a quickly written arrow function like the following:
//script.js
! function() {
var addTextNode = (ele, text) => { //create function addTextNode with 2 arguments
document.querySelector(`${ele}`).appendChild(document.createTextNode(`${text}`));
// ^ Tell the function to add a text node to the specified dom element.
}
addTextNode("body", "Hello World");
}();
Here's a JS Fiddle that also shows you how to append to other elements using the same function.
Hope this helps!
There are multiple ways to ways to solve your problem. The first way only changes your javascript. It uses the document.write() function to write the text to the document.
Here is the new javascript:
window.onload = function() {
document.write("Hello World!");
};
The second way also only changes your javascript. It uses the document.createElement() function to create a p tag and then changes the content inside it then appends it to the body.
Here is the new javascript:
window.onload = function() {
var p=document.createElement("p");
p.innerHTML="Hello World!";
document.body.appendChild(p);
};
window.onload = function() {
document.write('Hello World')
};
Returning from window.onload doesn't do anything productive. You need to call methods on the document to manipulate the page.
I have this code in razror view page:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">
Click me</button>
<p id="demo">
</p>
#{
List<UserContact> userContacts = ViewBag.contacts;
String contacts1 = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
}
<script type="text/javascript">
var contacts2 = #contacts1;
function myFunction() {
alert(contacts2);
}
</script>
</body>
</html>
when I press button Click me I get this error:
ReferenceError: myFunction is not defined
Why I get this error?
Any idea why I get this error?
Looks like you have some pretty broken HTML. You have assigned the contacts1 server side variable to an HTML fragment:
String contacts1 = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
and then you injected it inside a tag:
<script type="text/javascript">
var contacts2 = #contacts1;
function myFunction() {
alert(contacts2);
}
</script>
which totally breaks your markup. Look at the source code of the generated page in the browser and you will see how broken it is.
And how can I fix it?
It's not quite clear what you are trying to achieve so it's pretty hard to say how to fix this issue, but for starters you might try having valid markup and javascript:
<script type="text/javascript">
function myFunction() {
alert('The button was clicked');
}
</script>
It looks like you are trying to load some markup from the server when the button is clicked. You might consider using AJAX if this is the case.
UPDATE:
It looks like you are trying to assign a server side string variable to a javascript variable. This can be done by properly encoding it:
<script type="text/javascript">
var contacts2 = #Json.Encode(contacts1);
function myFunction() {
alert(contacts2);
}
</script>