JS function does not update HTML string - javascript

Im pretty new to JS and HTML (started ~20 hours ago) and already have a problem: below you can see my code. As one tutorial said, clicking on button will change the statusLine text. But something went wrong and i cant figure it out.
<!DOCTYPE html>
<html>
<head>
<title>Некое подземелье</title>
</head>
<body>
<p id="statusLine">Вы попали в подземелье.</p>
<button type="button" onclick="goDeeper()">Идти глубже в подземелье</button>
<script>
function goDeeper()
{
var nextEvent=(Math.floor(Math.random()*10+1));
switch(nextEvent){
case'1':
document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
break;
}
}
</script>
</body>
</html>
So, something is wrong. What should i do in order to fix this?

Try making the case statement match the number 1 rather than the string '1':
function goDeeper()
{
var nextEvent = Math.floor(Math.random()*10+1);
switch(nextEvent) {
case 1:
document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
break;
}
}
Or for that matter, if there is only one condition you need to match, just get rid of the switch and use a simple if block:
function goDeeper()
{
var nextEvent = Math.floor(Math.random()*10+1);
if (nextEvent == 1) {
document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
}
}

What I understand you want to change the text on click button so Try this
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="Hello World";
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>`enter code here`
</body>
</html>
Refrence Link : http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick

Related

Javascript if statement issue: No display in the webpage

I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>

How do i increment a global variable in a function in java script from a button?

this might be a dumb thing to ask but I am getting a lot of trouble with this for and quiz I need to make for and assignment, and I am trying to increment the score when the user clicks to the correct button. However, the score is not incrementing. here is a little sample of what it looks like.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Increment Button</title>
</head>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore()
{
score++;
}
console.log(score);
</script>
</body>
</html>
You have a few issues.
You probably want to console.log from within the IncrementScore function.
You want to increment the variable using += 1 or ++.
<!DOCTYPE html>
<html>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore() {
score++;
console.log(score);
}
console.log(score);
</script>
</body>
</html>
Change your code to score += 1 and move you console call to inside of your function.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Increment Button</title>
</head>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore()
{
score += 1;
console.log(score);
}
console.log(score);
</script>
</body>
</html>
On each click you increment variable. And in next line assign to variable "1". You should delete line
score = 1;
TL;DR: Actually the score did increment, but not be printed out via the click handler.
As I know in your snippet, all your script in <script> tag (include console.log) will all execute once initially. Then it sits there to listen to the events, like your click. Then when you click on the button, the IncrementScore function is called, it increments the score variable, but not print it out. You know why? because you don't tell it to do so, (in the IncrementScore handler). If you notice, you'll see that you only have one 0 printed out, not each 0 per click.
You should read about the call stack,etc.. to know more about the order which code is executed...
The fixes snippet can be found in other's answer, here is the code for when the variable actually "does not change", and be printed out for each click.
<!DOCTYPE html>
<html>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore() {
//score++;
console.log(score);
}
</script>
</body>
</html>

Why is my script not working in this html document?

I'm new to programming and I'm teaching myself HTML and Javascript as well as python.
I got to a point in learning these languages were I felt like I could do one of the things I was working on in html using javascript.
I ran into a problem where for whatever reason my code simply isn't working.
I double checked everything and I'm pretty sure it's all in the right place and all of the characters are correct.
Here is my code so far in it's entirety. I'm still pretty early in development and I understand that this isn't complete.
<!doctype html>
<html>
<head>
<title>Python game</title>
</head>
<body>
<p>Enter your choice by clicking on the buttons below the paragraph<p>
<p id="newText">kjgkhg</p>
<button type="onClick" id="ChooseFirst">First choice</button>
<button type="onclick" id="chooseSecond">Second choice</button>
<button type="onclick" id="choosethird">Third choice</button>
<script>
document.getElementById("newText").innerHTML = "why doesn't this work?";
funciton darkRoom() {
vars x=document.getElementById("newText").innerHTML ;
document.getElementById("newText").innerHTML = "You wake up in a dark room with no \
idea how you go there. You can make out the outline of three doors\
labeled '1', '2', and '3' directly in front of you. There is no door behind you.\
Which door do you enter?";
}
function lions() {
}
function tiger() {
}
functoin bear() {
}
function brickRoad() {
}
function quickSand() {
}
function sizePuzzle() {
}
function riddlesOnWall() {
}
function wolfSheepCabbage() {
}
function duckHunt() {
}
function hangman() {
}
function goldRoom() {
}
function ocean {
}
function winScreen () {
}
function youDie() {
}
</script>
</body>
</html>
There are a lot typos in it as Chris L already pointed out and as much as Juhana is right but the errors printed in the console are hard to decipher for a beginner (although you have to learn them, especially as a beginner!).
Here is some stripped down template you can play with
<!doctype html>
<html>
<head>
<title>Python game</title>
<script>
function darkRoom() {
var x=document.getElementById("newText").innerHTML ;
// You cannot escape the end-of-lines you have to concatenate individual strings
document.getElementById("newText").innerHTML = "You wake up in a dark room with no " +
"idea how you go there. You can make out the outline of three doors" +
"labeled '1', '2', and '3' directly in front of you. There is no door behind you." +
"Which door do you enter?";
}
// instead of alert() call another function reacting to the users input
function firstChoosen() {alert("first choosen");}
function secondChoosen() {alert("second choosen");}
function thirdChoosen() {alert("third choosen");}
</script>
</head>
<body onload="darkRoom()">
<p>Enter your choice by clicking on the buttons below the paragraph<p>
<p id="newText"> </p>
<!-- there are better methods but it's ok for now -->
<button onclick="firstChoosen()" id="ChooseFirst">First choice</button>
<button onclick="secondChoosen()" id="chooseSecond">Second choice</button>
<button onclick="thirdChoosen()" id="choosethird">Third choice</button>
</body>
</html>

the string str is always empty although it is filled with data from the.geojson file any idea?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#p1").load("reporting/data.geojson").toString();
var str = document.getElementById("p1").innerHTML;
document.getElementById("p2").innerHTML = str;
});
</script>
</head>
<body>
<div id="div1">
<h2>try</h2>
</div>
<p id="p1"></p>
<p id="p2"></p>
</body>
</html>
this is the code, p1 clearly shows on the screen but my actual problem is that i cant fill the string with it, "maybe the load function is the last to act i dont know" kinda new on this. I need to put the .geojson text in a string, or any other way to extract the coordinates would save me the trouble of string eddting. thank you iij advance
You need to use the callback of load to get the data from #p1.
The load method is asynchronous, so the code does not wait for the data to load and executes the next statement.
$(document).ready(function() {
$("#p1").load("reporting/data.geojson", function() {
var str = document.getElementById("p1").innerHTML;
document.getElementById("p2").innerHTML = str;
});
});
As you're using jQuery, you can use html()
$(document).ready(function () {
$("#p1").load("reporting/data.geojson", function () {
$('#p2').html($('#p1').html());
});
});

Why does the browser modify the ID of an HTML element that contains &#x?

Say I've got this HTML page:
<html>
<head>
<script type="text/javascript">
function echoValue(){
var e = document.getElementById("/path/$whatever");
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
I would assume that the browser treats the ID-string /path/$whatever as simple string. Actually, it converts the $ to it's rendered representation ($).
The javascript code however uses the literal string $ to search for the element. So, the call document.getElementById fails and I never get hands on the value of the paragraph.
Is there a way to force the browser into using the given ID string literally?
Edit:
Of course I know that I don't have to escape the $. But the web page gets generated and the generator does the escaping. So, I have to cope with what I've got.
In the <p id="...">, the $ sequence is interpreted as $, because it appears in an attribute and is treated as an HTML entity. Same goes for all other element attributes.
In the <script> element, HTML entities are not interpreted at all, so it shows up literally.
You could try decoding the javascript text without jQuery:
<html>
<head>
<script type="text/javascript">
function decodeEntity(text){
text = text.replace(/<(.*?)>/g,''); // strip out all HTML tags, to prevent possible XSS
var div = document.createElement('div');
div.innerHTML = text;
return div.textContent?div.textContent:div.innerText;
}
function echoValue(){
var e = document.getElementById(decodeEntity("/path/$whatever"));
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
JSFiddle: http://jsfiddle.net/phTkC/
I'd suggest you to decode the HTML entity in your javascript code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
function echoValue(){
var decoded_string = $('<div />').html("/path/$whatever").text();
var e = document.getElementById(decoded_string);
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>

Categories