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>
Related
I am new just started a course on JS and wanted to have fun on an assignment but perhaps got a little ahead of myself. I decided to do a simple recreation of The Bridge of Death from Monty Python
I am trying to use JS in a HTML file to create a dropdown menu and then when a certain option is selected it changes the color of the paragraph elements.
I am unsure how to pull the values of the options created in the select form to style the element.
What I have now creates the dropdown but the options don't change anything
Sorry if this is super janky, I literally started a week ago.
Here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>
<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>
<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>
<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>
<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = list.options[list.selectedIndex].values;
document.p.style.backgroundColor = val;
}
</script>
<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.onchange = "changeBackground(this)";
for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";
document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>
</html>
I feel like there is a better way to create the select form. I could also use html to create it and then hide then reveal it in the q2_func.
Any suggestions on where I could go from here?
Some limitations based on the assignment: no seperate files for js or css, just use js to change the style (no jquery or ajax)
Also the "blue...no..." should lead to an alert but that isn't working either...
Thank you in advance!
-Kevin
Here's your code solution.
If you want to add onchange function you need to use setAttribute function to add onchange function on selectbox in q3_func().
You didn't defined any list veriable in changeBackground function that you want to use in that function event that you're getting colors parameter and you can use colors.options and colors.selectIndex
You can't use document.p directly because p is not defined as veriable or it's not a document but it's a part of document. You can use document.getElementsByTagName('p')[0] [0] indecate index of tags.
For example:
Your are using p tag 5 time in body [0] indecates first p tag and [1] indecates to 2nd.
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>
<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>
<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>
<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>
<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = colors.options[colors.selectedIndex].values;
document.getElementsByTagName('p')[0].style.backgroundColor = val;
}
</script>
<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.setAttribute("onchange", "changeBackground(this)");
for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";
document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>
</html>
I hope you understand this.
I figured out the alert trigger!
Using the changes Abdul made I added the following code to the end of the changeBackground function:
var x = document.getElementById("colors").selectedIndex;
var y = document.getElementById("colors").options;
if (y[x].index === 4){
alert("Ahhhhgggg!!! .... *Death*");
};
It works completely now.
Thank you
Kevin
Okay, so I'm trying to create a quiz application for revision purposes that asks a random question from a list of questions, takes a text input as the users answer to the question, and then compares it to the actual answer to the question. The code I have used is:
var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;
var answerValidation = function(correctAnswer, userAnswer) {
correctAnswer = htmlModule[ranPropName][1];
userAnswer = document.getElementById("submit").value;;
if(userAnswer === correctAnswer) {
document.getElementById("rightWrong").style.backgroundColor = "green";
} else {
document.getElementById("rightWrong").style.backgroundColor = "red";
}
};
The variable htmlModule refers to the object in which the questions and their answers are stored. Each question and answer pair is stored inside an array that is the value of its property, the property simply being a key used to reference each pair e.g. htmlQ1, htmlQ2 etc.
The main problem I seem to be having is that my if statement comparing the actual answer and the user answer won't evaluate to true. I know this because the background colour of the div element rightWrong only ever turns red, even when I've definitely typed in a correct answer at which point it should turn green. My assumption is that either the text input isn't being stored for some reason, or the value of the variable ranPropName that uses Math.random() is changing due to the use of Math.method(), but I'm stuck as to how to remedy either potential problem. Thanks in advance for any replies.
Well, I started to visualize your quiz as you explained.
One thing is need to be changed is that you get userAnswer from the value of an element with Id submit which I assume most probably it's an button tag, so I write a working code sample as follow:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
</head>
<body>
<input type="text" id="rightWrong" />
<div id="question" />
<button id="submit">Submit</button>
</body>
<script>
var htmlModule = {
'htmlQ1': ['1+1=?', '2'],
'htmlQ2': ['2+2=?', '4']
};
var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;
var answerValidation = function(correctAnswer, userAnswer) {
correctAnswer = htmlModule[ranPropName][1];
userAnswer = document.getElementById("rightWrong").value;
if(userAnswer === correctAnswer) {
document.getElementById("rightWrong").style.backgroundColor = "green";
} else {
document.getElementById("rightWrong").style.backgroundColor = "red";
}
};
</script>
</html>
Please share your html if you still face problems.
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.
So I have a variable in my script var mystring = "123" and my web page look like this
<body>
<div id="footer">
123
</div> </body>
I need a script that checks if the variable is the same as the footer content and if is not, replace it.
Just like this :
a="123";
if a == html.content.from.footer then
do nothing;
else
replace html.content.from.footer with a;
There's no need to check if the values are equal, because if you replace a value with an equal value then there's no change anyway. So all you really need to do is replace the value. Something like this:
document.getElementById('footer').innerHTML = mystring;
Using jQuery, this is simple:
if($("#footer").html() !== mystring) {
$("#footer").html(mystring)
}
Without jQuery:
if(document.getElementById('footer').innerHTML !== mystring) {
document.getElementById('footer').innerHTML = mystring;
}
Here,
<script>
var mystring = "123";
var footer = document.getElementById("footer");
if(footer.innerHTML != mystring){
footer.innderHTML = mystring;
}
</script>
PS. I agree with David that you don't need to check if you know the string you want in the footer anyway. Just adding the script with the if block because you asked it that way. Hope this helps.
var myVar = '1234';
var element = document.getElementById('footer');
if(myVar != element.innerHTML) {
element.innerHTML = myVar;
}
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);