I wrote an example on Javascript function fiddle, but there is no output, how can I solve this mistake.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function student(name,id,level,phone){
var name, id, level, phone;
this.name= name;
this.id= id;
this.level= level;
this.phone= phone;}
function myFunction(){
var stud = new student("khaled al gamd","110_35_1353","three",0501607419);
var name= stud.(name);
var id= stud.(id);
var level= stud.(level);
var phone= stud.(phone);
document.write (name);
document.write (id);
document.write (phone);
}
<p id="result"><\/p>
document.getElementById("result").innerHTML=myFunction();
</script>
</body>
</html>
You need to write out that paragraph tag if you want to create it through JavaScript:
function student(name, id, level, phone) {
this.name = name;
this.id = id;
this.level = level;
this.phone = phone;
}
function myFunction() {
var stud = new student("khaled al gamd", "110_35_1353", "three", 0501607419);
var name = stud.name;
var id = stud.id;
var level = stud.level;
var phone = stud.phone;
return name + "<br>" + id + "<br>" + phone;
}
document.write('<p id="result"> </p>');
document.getElementById("result").innerHTML = myFunction();
For help on JavaScript, you can try JSHint:
http://jshint.com/
Your JavaScript with html together.
Try this:
<html>
<head>
</head>
<body>
<p id="result">
<script type="text/javascript">
function student(name,id,level,phone){
this.name= name;
this.id= id;
this.level= level;
this.phone= phone;
}
function myFunction(){
var stud = new student("khaled al gamd","110_35_1353","three",0501607419);
var name= stud.name;
var id= stud.id;
var level= stud.level;
var phone= stud.phone;
document.write(name);
document.write(id);
document.write(phone);}
myFunction();
</script>
</p>
</body></html>
The other answers here are correct, but neither of them explain why they are correct so here's a little explanation.
Here is a working version of your code:
<html>
<head>
</head>
<body>
<p id="result"></p>
<script type="text/javascript">
function student(name,id,level,phone){
var name, id, level, phone;
this.name= name;
this.id= id;
this.level= level;
this.phone= phone;
}
function myFunction(){
var stud = new student("khaled al gamd","110_35_1353","three",0501607419);
var name= stud.name;
var id= stud.id;
var level= stud.level;
var phone= stud.phone;
return name + id + phone;
}
document.getElementById("result").innerHTML=myFunction();
</script>
</body></html>
Now, there were a few issues with your example. Firstly, you were trying to access attributes of the student object like this: stud.(name) which is not valid syntax. The correct syntax for this is: stud.name.
Secondly, you were declaring html elements inside your script tags. Everything inside the script tags should be valid javascript, which this is not. You have two alternatives, one is to move that line outside the script tags (inside the body, above your script or it won't be created until after the script is run), the other is to create the elements with javascript as in the answer by #Emil S. Jørgensen.
Thirdly, you were trying to set the inner html of the element to the result of the function, but the function did not return anything to display. Rather it tried to write directly to the document. This will give you some output, but it will not be inside the element that you are aiming for. Instead what you need to do is to return some valid html from the function (although this does not necessarily have to contain any html elements).
Correct these issues and it should work as expected. One side note though, your code is not well formatted which makes it harder to read and harder to spot problems. I would suggest you take care in formatting your code in future.
Related
This my code..
<!DOCTYPE html>
<html>
<head>
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name ").value;
var school_site= document.getElementById("school_site ").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>
<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br> <input type="text" name="name" id="name"></p>
<p>School Website:</br> <input type="text" name="school_site" id="school_site"></p>
<p>School Name:</br> <input type="text" name="school_name" id="school_name"></p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
"content" is the javascript variable.
I need to assign HTML code as value for "content" variable,
And i also need to add some Javascript variable inside the HTML
code,
How to add javascript variable in html Hypertext link?
There are many ways to achieve this. For a simple use-case, you can use an array of string to perform work and at the end you can join with "" or "\n".
var template = [
"<h2>Student Details:</h2>",
"<div align='justify'><p>"+name+"is studing in "+school_name+"</p>",
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>"
].join("<br/>");
For more complex case, I will say use jquery or Plain JavaScript method. As given below.
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
//jQuery:
var node = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
);
//Plain JavaScript
var h2 = document.createElement("h2");
h2.textContent = "Student Details:";
var div = document.createElement("div");
var p1 = document.createElement("p");
p1.textContent = name+"is studing in "+school_name;
var p2 = document.createElement("p");
p2.textContent = "Visit site: ";
div.appendChild(p1);
div.appendChild(p2);
//add attribute node
var node = document.getElementById("div1");
var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
//Once done return as string
return div.outerHTML;
}
You have extra space in id in school_name and school_site`.
So it is not being recognized and you are getting exception. Also your syntax to concatenate string is also incorrect.
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
Your full javascript code would be like this
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>"+
"<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
You can write a string on multiple lines using template literals, i.e. using the character " ` ".
You can easily integrate variables using ${yourVar} in the template literal
Example:
let lit = "literal";
var content = `This string
uses a template ${lit}`;
console.log(content);
Note: this is an ES6 feature, aka the not so new JavaScript that is not yet fully supported by browsers. To make this code compatible with older browsers, use a transpiler like babel
You have to use <br> instead of '/n' while assigning to javascript variable.
The problem as I see it is you have hit enter in the mid of string and you have extra space in the id selector.
Don't hit enter or use tilt ` to declare string instead of quotes.
<!DOCTYPE html>
<html>
<head>
<script>
function generate() {
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site = document.getElementById("school_site").value;
var content = "<h2>Student Details:</h2>" +
"<div align='justify'><p>" + name + "is studing in " + school_name + "</p>" +
"<p>Visit site: <a href='http://" + school_site + "'>http://" + school_site + "</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br>
<input type="text" name="name" id="name">
</p>
<p>School Website:</br>
<input type="text" name="school_site" id="school_site">
</p>
<p>School Name:</br>
<input type="text" name="school_name" id="school_name">
</p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
Suggestion : No need to use /n for new line, h2 is block element no need of break too.
Something weird is happening here.
My website is using javascript to create dynamic divs, but although they are entered into the DOM (at least this is what I think), javascript returns null when calling that div.
This is the javscript code which is loaded before </body>
function AddPlayer(){
var name = document.getElementById('name').value;
createBox(name);
};
function createBox(name){
var span = document.createElement('span');
span.id = name;
span.innerHTML = name;
document.getElementById("gameArea").appendChild(span);
var span = document.createElement('span');
span.id = "score-" + name;
span.innerHTML = "0";
document.getElementById("gameArea").appendChild(span);
var inputSText = document.createElement('input');
inputSText.type = "button";
inputSText.value = "Add Points";
inputSText.onclick = function(){AddPoints(name);};
document.getElementById("gameArea").appendChild(inputSText);
};
function AddPoints(player){
document.load(document.getElementById("#score-"+ player).innerHTML = "Please work");
};
<html>
<head>
<title>Game Score Keeper</title>
</head>
<body>
<h2>Game Score Keeper</h2>
<input type="text" id="name" />
<input type="button" value="Add Player" onclick="AddPlayer()" />
<div id="gameArea">
</div>
<script src="index.js"></script>
</body>
</html>
Here is the jsfiddle of this project http://jsfiddle.net/jwmm6rk7/
You need to pass the id of the element to document.getElementById. That is, without the hash (#) symbol.
function AddPoints(player) {
document.load(document.getElementById("score-" + player).innerHTML = "HELLO");
};
lookslike you were jQuery user, you used # and name instead of player
function AddPoints(player) {
document.getElementById("score-" + player).innerHTML = "HELLO";
};
I am new to javascript so please forgive me if this is a simple answer. I cannot seem to find it. I have a small block of script that replaces text based on the content of the paragraph. Very easy. My questions is, why do I have to right out the entire reference twice? Does the variable not point to the same thing? Is there a simpler way?
This works:
<p id="name">Electric City</p>
<script type="text/javascript">
var name = document.getElementById("name").innerHTML;
if (name == "Electric City") {
document.getElementById("name").innerHTML = "Welcome!";
}
</script>
This doesn't:
<p id="name">Electric City</p>
<script type="text/javascript">
var name = document.getElementById("name").innerHTML;
if (name == "Electric City") {
name = "Welcome!";
}
</script>
Thank you!
var name = document.getElementById("name").innerHTML;
That line of code gets the value from your "name" element (using its innerHTML property) and copies it to the variable name. The name variable does not refer to the "name" element itself.
If you want to simplify your code, you could do something like this:
<script type="text/javascript">
var nameElement = document.getElementById("name");
if (nameElement.innerHTML == "Electric City") {
nameElement.innerHTML = "Welcome!";
}
</script>
In JavaScript, saying variable = value doesn't affect the thing that variable originally referred to. Saying variable.property = value does affect the thing that variable refers to.
So to simplify the code, do this:
var element = document.getElementById("name");
if (element.innerHTML == "Electric City") {
element.innerHTML = "Welcome!";
}
Example
Try this:
<script type="text/javascript">
var name = document.getElementById("name");
if (name.innerHTML == "Electric City") {
name.innerHTML = "Welcome!";
}
</script>
name is only holding the value and isn't referencing the actual element as a whole.
You need to grab the element THEN check and apply the innerHTML to it.
Try this:
var elem = document.getElementById("name");
if (elem.innerHTML == "Electric City") {
elem.innerHTML = "Welcome!";
}
The problem is that you had a reference to a string, not a reference to the object that holds the string. Since strings are immutable, setting a new value of a string variable just creates a whole new string and leaves the original (that was referred to my your element) untouched.
as simple as this
<p id="demo">Electric City</p>
<script>
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/Electric City/gi," Welcome!");
document.getElementById("demo").innerHTML=res;
</script>
or
<script>
var str = document.getElementById("demo");
var res = str.innerHTML.replace(/Electric City/gi," Welcome!");
str.innerHTML=res;
</script>
I'm completely new to javascript and a friend helped me with a problem, I know what it does but I can't really understand some parts, I've made some comments in the code with some questions I hope you can answer them.
<html>
<head>
<title>Uppgift 15</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
var resultat = 0;
function addera(){
var t1 = Math.round(object("t1").value);
if (t1 != 0){
resultat += t1;
object("t1").value = "";
}
else{
object("resultat").innerHTML = resultat; // where does "object" come from, what does innerHTML do?
}
}
function object(id){ // i dont get this at all what does this do is there any other way to return?
return document.getElementById(id);
}
</script>
</head>
<body>
<form>
<input id="t1">
<input type="button" onClick=addera() value="resultat">
<p id="resultat"></p>
</form>
</body>
</html>
The object function returns the html element with the specified ID, while innerHtml lets you edit the HTML associated to that element
The object() is already defined in your code, in which document.getElementById(id); will return the element with the specified ID.
The innerHTML property sets or returns the inner HTML of an element.
Here object("resultat").innerHTML = resultat;
Is same as
document.getElementById("resultat").innerHTML = resultat;
the object is returned from your object function your function simply gets element by id from dom and returns it
var resultat = 0;
function addera(){
var t1 = Math.round(object("t1").value);
if (t1 != 0){
resultat += t1;
object("t1").value = "";
}
else{
object("resultat").innerHTML = resultat; // object is returned from object function according to parameter of function the function takes this parameter as id
and selects the element from dom
}
}
function object(id){
return document.getElementById(id);
}
I'm attempting to make a simple linear text game that will display inside a div on a webpage. I am using innerHTML to write the contents of the game to the div, and using onclick from a button to change the contents. My problem is that I would also like to include a few user-submitted variables, which I am trying to do using prompt() inside a function.
The problem is, I can't get the variable to set globally. It works when called inside the function, but nowhere else.
I've tried declaring the variable first outside the function, using window.variable (both inside and outside of the function) as well as leaving off the var before the variable inside the function to make it global in scope.
I have looked for solutions and nothing seems to work! Am I missing something with the order of my script?
Here is the javascript:
var cb2 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next3,\'continueBttn\',cb3);">';
var cb3 = '<input id="button" type="button" value="Continue" onclick="getName();">';
var cb4 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next5,\'continueBttn\',cb5);">';
var cb5 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next6,\'continueBttn\',cb6);">';
var testName = "Test Name";
var player1;
var next2 = "<p>Great, you've certainly got an adventurer's spirit! Now I just need a few details about you and your party.</p>";
var next3 = "<p>First, I'd like to get everyone's name</p>"
var next4 = "<p>Thanks " + testName + "!</p>"
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
var continueButton = function (content) {
document.getElementById('continueBttn').innerHTML = content;
};
function replace(id1,content,id2,cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
function getName() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox',next4,'continueBttn',cb4);
}
And here is the html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="oregon.css" />
</head>
<body>
<div id="gameContainer">
<div id="gamebox">
<p>Welcome to the Oregon Trail! Click Continue to travel the trail!</p>
</div>
</div>
<div id="continueBttn"><input id="button" type="button" value="Continue" onclick="replace('gamebox',next2,'continueBttn',cb2);"></div>
</body>
</html>
<script src="oregon.js" type="text/javascript"></script>
Ok, I got your stuff to work. Take the var off of the variables to make them global and change your functions to be assigned to a variable like continueButton:
replace = function(id1, content, id2, cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
getName = function() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox', next4, 'continueBttn', cb4);
}
This got things working for me.
The other answers here have good points as well, you need a better way of handling the player name.
player1 is used into the expression next5, not next4 (which is the one of your getName() function)
Anyway, it will never work like this. At the moment next5 is initialized the value of player1 was defined a certain way, and will remain defined that way unless you redefine the next5 variable again.
You need to encapsulate the next5 definition into a function in order to make it dynamic.
Problem is here
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
It uses the variable when it is first rendered, it will not be updated when you set player1 to a new value.
You need to figure out a different way to set the player's name. One way of doing it is to replace it.
var next5 = "<p>Now you're ready {player1}! Click to set out on the trail!</p>"
and when you use it
var newStr = next5.replace("{player1}", player1);