I keep getting undefined before my output text in JS.
Here is my code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learning javascript</title>
</head>
<body>
<p id="arrayString"></p>
<!-- Javascript -->
<script type="text/javascript" src="JS/app2.js"></script>
</body>
</html>
This is my JS
var arrayString;
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
for (var i=0; i<myArray.length; i++) {
arrayString=arrayString+myArray[i];
}
document.getElementById("arrayString").innerHTML=arrayString;
my output is undefinedMs.VickiesOld DutchLays
In addition why no spaces? I am new to JS but am working my way up. Cannot figure this out.
It's because in your first loop iteration, arrayString is undefined. Set it equal to an empty string instead.
Instead of declaring arrayString like so:
var arrayString;
Initialize it with an empty string:
var arrayString = '';
Because you are initiating a null/undefined variable by doing this: var arrayString;
You can fix it by doing this: var arrayString = "";
Better yet, instead of using a for loop, you can do it like this:
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
document.getElementById("arrayString").innerHTML = myArray.join(" ");
More info: http://www.w3schools.com/jsref/jsref_join.asp
In code ,you have just declared,not initialized.so,just replace
var arrayString;
with
var arrayString = '';
Hope it helps...Thank you.
Related
I want to make a Hangman game so I can learn JavaScript, I don't know how to change the innerHTML
of the char I made in js. So when I know if the string includes the guess then i want to make the line which represents the correct guess to transform into a charater and make it apear but when i run the code it turns the last of the lines into the correct guess and makes it disapear when there's a new guess and transforms the line into second correct guess. And doesn't reconizez 'o'(the last character that is in the string)
I would like to apologize if I made grammer mistakes.
//defineing the word
var a = 'hello';
// makes the lines
for ( var i=0; i<a.length; i++){
var letter = document.createElement("h3");
letter.className = 'letter'+i;
var j = 2*i+23;
letter.style ="position: absolute;"+"top: 14%;"+"left: "+j+"%;";
letter.innerHTML = "_";
document.body.appendChild(letter);
}
//submit btn gets the input and if it's correct shows it, if it isn't correct than puts into a wrong words
function submt(a,letter){
var inpt = document.getElementById('input');
if (a.includes(inpt.value)){
letter.innerHTML = a[a.indexOf(inpt.value)];
}else {
console.log('wrong')
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hangman</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Yanone+Kaffeesatz:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<p class='letter'>Write the letter in here:</p>
<p class='bad'> the wrong letters:</p>
<p class='word'>the word:</p>
<input type="text" class="input" id="input">
<button class="sub" id='submit' onclick="submt(a,letter)">submit</button>
<script src="script.js"></script>
</body>
</html>
You were resetting the letter variable to the last h3 element. You needed a array for each of the slots.
//defineing the word
var a = 'hello';
// makes the lines
var letters = []; // this array store the h3 elements
for ( var i=0; i<a.length; i++){
var letter = document.createElement("h3");
letter.className = 'letter'+i;
var j = 2*i+23;
letter.style ="position: absolute;"+"top: 14%;"+"left: "+j+"%;";
letter.innerHTML = "_";
document.body.appendChild(letter);
letters.push(letter); // add element to array
}
//submit btn gets the input and if it's correct shows it, if it isn't correct than puts into a wrong words
function submt(a,letter){
var inpt = document.getElementById('input');
if (a.includes(inpt.value)){
var l = 0, result = [];
while (l<a.split('').length) {
if (a.split('')[l] == inpt.value) { // a split('') turns the word into an array so it is easier to search
result.push(l); // this store the position of the correct letter in the word
}
l++;
}
var l = 0;
while (l<result.length) {
letters[result[l]].innerHTML = a.split('')[result[l]]; // change the h3 elements content to the correct letter using the result array.
l++;
}
}else {
console.log('wrong')
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hangman</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Yanone+Kaffeesatz:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<p class='letter'>Write the letter in here:</p>
<p class='bad'> the wrong letters:</p>
<p class='word'>the word:</p>
<input type="text" class="input" id="input">
<button class="sub" id='submit' onclick="submt(a,letter)">submit</button>
<script src="script.js"></script>
</body>
</html>
You are currently accessing always the last dash created.
Thats because createElement will create a h3 element for each char in the word.
for ( var i=0; i<a.length; i++){
var letter = document.createElement("h3");
...
}
After the loop the variable var letter will contain the last h3 element created. You defined letter inside a for loop but access it inside a method.
It works in javascript but is a bit unexpected to see.
I assume you are not yet familiar with scopes. That is okay for now but maybe also something you want to read about for future progress.
https://www.w3schools.com/js/js_scope.asp
A solution close to your solution, but which uses an array to save all h3 elements.
Note that I also removed the parameters of submt() because you did not use them.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hangman</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Yanone+Kaffeesatz:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<p class='letter'>Write the letter in here:</p>
<p class='bad'> the wrong letters:</p>
<p class='word'>the word:</p>
<input type="text" class="input" id="input">
<button class="sub" id='submit' onclick="submt()">submit</button>
<script src="script.js"></script>
</body>
</html>
//defineing the word
var a = 'hello';
// makes the lines
var letters = []
for ( var i=0; i<a.length; i++){
var letter = document.createElement("h3");
letter.className = 'letter'+i;
var j = 2*i+23;
letter.style ="position: absolute;"+"top: 14%;"+"left: "+j+"%;";
letter.innerHTML = "_";
document.body.appendChild(letter);
letters.push(letter)
}
function submt(){
var inpt = document.getElementById('input');
if (a.includes(inpt.value)){
var index = a.indexOf(inpt.value)
letters[index].innerHTML = a[index];
}else {
console.log('wrong')
}
}
I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!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>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!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>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>
I am a newbie to JavaScript < 1 Week old
I wrote a very short HTML/JavaScript and got it to display on console.
Basically, I want to display the result of a function used as a variable inside the <p> tag of the HTML.
I got the script to display in the console.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
</script>
<script>
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
</script>
<p id="Kilograms"><!--I want the result here--></p>
</body>
</html>
How do I get the result of the function as a variable i.e var kilo (pounds)... to display in the p tag with id Kilograms?
Script shold be after BODY code, or you should add document ready event listener. So, try this solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="Kilograms"><!--I want the result here--></p>
</body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
document.getElementById("Kilograms").innerHTML = kilog(440);
</script>
</html>
Example in JSBin: https://jsbin.com/pacovasuve/edit?html,output
You can try this in your js code.
document.getElementById("Kilograms").innerHTML="write whatever you want here";
Try this
var p = document.getElementById('Kilograms');
p.innerHtml = 'any text';
// OR
p.innerHtml = kilog(440);
I have a table with the following data.
description
object 1
object 2
object 3
I try to get this data from my database via socket.io and put the data into a string variable called Objects. The string Objects will look like this object1,object2,object3.
If I try to do alert(objects) the string is undefined.
My HTML code is
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="/examples/examples.css" type="text/css"/>
</head>
<body>
<script src="/lib/jquery-1.7.min.js"></script>
<script src="/lib/jquery.event.drag-2.2.js"></script>
<script src="../lib/jquery-ui-1.8.16.custom.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var objects;
var temp=[];
socket.on('load data', function(data){
for (var i = 0; i < data.length; i++) {
temp = data[i];
objects = objects + "," + temp.description;
};
objects = objects.substr(10, objects.length-10);
objects=$.trim(objects);
});
alert(objects); <== undefined
})
</script>
</body>
</html>
I tried document ready (see here below) since alert(objects) is executed before the socket.io, but this doesn't help.
$( document ).ready(function() {
alert(objects);
});
How should I solve this issue?
Thank you for your time!!
You should consider using the socket.io debugging tool inside of the chrome debugger.
$(function(){ // don't pass $ as an argument to this function
var socket = io.connect(), // what are you connecting to?
objects,
temp=[];
socket.on('load data', function(data){
for (var i = 0; i < data.length; i++) {
temp = data[i];
objects = objects + "," + temp.description;
};
objects = objects.substr(10, objects.length-10);
objects=$.trim(objects);
alert(objects); // what is the value of objects here?
});
alert(objects); // socket.on is asynchronous so this line is will pretty much always
// be executed before your callback function for socket.on()
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
<script language="JavaScript">
<!--
function showtags()
{
var tag;
for(i = 0; i < document.all.length; i++)
{
tag = document.all(i).tagName;
document.write(tag + ' ');
//document.write("<br>");
}
}
// -->
</script>
</head>
<body>
<script>
showtags();
</script>
</body>
</html>
If I un-comment the second document.write() in the loop inside the function then it hangs (it does not display anything and times out). I appreciate your help.
document.all is a "live" collection. Each time you loop, you add 2 new items. This means every time it evaluates the length property it's always going to be larger than i.