Print array to textarea in JavaScript - javascript

I'm trying to print an array to a textarea in JavaScript. My current code only prints the first element instead of all four, and I don't know why.I have tried using a regular for loop as well, but that doesn't make a difference.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var listArray = function()
{
var people = ["Ben", "Joel", "Mary", "Tina"];
var scores = [88, 98, 100, 78];
for (var key in people)
{
var obj = people[key];
var num = scores[key];
var string = obj + ", " + num + "\n";
document.getElementById("box").innerHTML = string;
}
}
window.onload = function()
{
document.getElementById("show_score").onclick = showHighScore;
document.getElementById("list_array").onclick = listArray;
}
</script>
</head>
<body>
<form id="high_score" name="high_score" action="highScore.html" method="get">
<label>Results</label>
<br>
<textarea cols="50" rows="4" id="box"></textarea>
<br>
<input type="button" value="List Array" id="list_array" onclick="listArray">
<br>
<input type="button" value="Show Best Score" id="show_score" onclick="showHighScore">
</form>
</body>
</html>

That is because of this line
document.getElementById("box").innerHTML = string;
So what you are saying, replace the content of textbox with the content of string. So at the end it just have the value of last element.
use this instead
document.getElementById("box").innerHTML += string;
So it will append the next record after previous one.
There is one more problem, on 23rd line it sasys showHighScore is not defined.

Related

How to loop in JavaScript

DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.
with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));
You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.

Uncaught ReferenceError: Invalid left-hand side in assignment. Javascript

I want to replace a character in a string (original) with another string.
I am getting an error on running the debugger.
I dont understand what is wrong with the syntax.
<!DOCTYPE>
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string<input id="original" value="" type="text"> <br>
Enter the replacing string<input id="replacing" value="" type="text"><br>
Enter the location to be replaced<input id="tobereplaced" value="" type="text"><br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br> Here you go the replaced string is:
<script>
function replace() {
var original = document.getElementById("original").value;
var replacing = document.getElementById("replacing").value;
var tobereplaced = document.getElementById("tobereplaced").value;
var replaced = "";
var originalLength = original.length;
var tobereplacedLength = tobereplaced.length;
var k = 0;
for (var i = 0; i < originalLength; i++) {
replaced.charAt(k) = original.charAt(i)
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
k = k + tobereplacedLength;
i++;
}
k++;
}
document.getElementById("replaced").innerHTML = replaced;
}
</script>
<h1 id="replaced"></h1>
</body>
</html>
you are trying to change the character of an empty string at line no:28 [replaced.charAt(k) = original.charAt(i)] this is the issue.
Also there are some unwanted increment in the code. please find the corrected below
I have updated the code below with // comment the code and added correct code. its working
// var k = 0; //Commented
// debugger; //Commented
for (var i = 0; i < originalLength; i++) {
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
// k = k + tobereplacedLength; //Commented
// i++; //Commented
} else{
replaced = replaced + original.charAt(i);
}
// k++; //Commented
}
Here is a more simplistic approach to the problem. It takes advantage of the .split() & .join() functions rather than using a for loop.
function replace() {
// set original string
var original = document.getElementById("original").value, // << use commas so you don't have to keep typing var
// set replacing string
replacing = document.getElementById("replacing").value,
// initialize newval
newValue,
// set replace position - this could also be called index
replacePosition = document.getElementById("tobereplaced").value; // << end variable declarations with semicolon
// split original string into array of characters
var splitOriginal = original.split("");
// use replacePosition as index value of character to replace
// & replace that character with replacing value
splitOriginal[replacePosition] = replacing;
// join array to form new string value
newValue = splitOriginal.join("");
document.getElementById("replaced").innerHTML = newValue;
}
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string
<input id="original" value="" type="text">
<br>Enter the replacing string
<input id="replacing" value="" type="text">
<br>Enter the location to be replaced
<input id="tobereplaced" value="" type="text">
<br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br>Here you go the replaced string is:
<h1 id="replaced"></h1>
</body>
</html>

How to assign Multiple line html code as a value to a javascript variable?

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.

User input stored in array using JavaScript

Hi guys i'm kinda new to javascript and for a while now, i've been struggeling with something that shouldnt be that hard. The thing that i'm trying to execute is to get user input stored in an array, and then get it to print the collected info into a specific div (later on i'm gonna try to create a table using the DOM and store the input there). But i cant get it to work, below is my code :) any suggestions?
JavaScript
function submitInfo(){
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.lenght; i++){
document.getElementById("theResult").innerHTML=myArray[i];
}
}
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="inl2a.css" />
<script type="text/javascript" src="inl2a.js"></script>
<title>Inlämning 2a</title>
</head>
<body>
<div id="inputFields">
<h3>Submit your fighters information:</h3>
Name:<br><br>
<input id="name" type="text" /><br><br>
Age:<br><br>
<input id="age" type="text" /><br><br>
Fighting style:<br><br>
<input id="fightingStyle" type="text" /><br><br>
Weight:<br><br>
<input id="weight" type="text" /><br><br>
<input id="button" value="Submit" type="button" onclick="submitInfo();" /><br><br>
</div>
<div id="theResult">
</div>
</body>
</html>
function submitInfo(){
var myArray = []; // problem 1
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.length; i++){ // problem 3
document.getElementById("theResult").innerHTML+=myArray[i]; // problem 2
}
}
you haven't initialized the array anywhere
you overwrite the innerHTML property so only the last value remains
you have a typo: lenght instead of length
You can also set the values directly in the array and no longer use the intermediary variables. Also, you can get theResult element once, outside of the loop:
function submitInfo(){
var myArray = []; // problem 1
myArray.push(document.getElementById("name").value);
myArray.push(document.getElementById("age").value);
myArray.push(document.getElementById("fightingStyle").value);
myArray.push(document.getElementById("weight").value);
var element = document.getElementById("theResult");
for(var i = 0; i<myArray.length; i++){
element.innerHTML += myArray[i]; // problem 2
}
}
suppose user inputs are title and name, then
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
You could put all of these in one array:
var m = [ title, name ];
then for title use,
document.getElementById(your_divID).innerText=m[0];
you can use textContent instead of innerText for mozilla support.

how to add text boxes dynamically without losing values of previous textboxes?

i am using innerHTML to add text boxes dynamically. The code sample is as follows:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
document.getElementById("y").innerHTML += tag;
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html
Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(
What if I want to add textbox in this situation:
function add() {
var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
document.getElementById("addskills").innerHTML += element;
i++;
}
Yes, through DOM Manipulation:
function add() {
var tag = document.createElement('input'); // Create a `input` element,
tag.setAttribute('type', 'text'); // Set it's `type` attribute,
tag.setAttribute('name', i); // Set it's `name` attribute,
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(tag); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.
(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)
Now, to add this:
<li class="ie7fix" style="width:620px;">
<div class="m_elementwrapper" style="float:left;">
<label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
<span>
<span class="pspan arial" style="text-align:right;font-size:14px;">
<span class="ispan" xml:space="preserve">
</span>
</span>
</span>
</label>
<div style="float:left;width:475px;" class="m_elementwrapper">
<input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent">
<div class="fielderror">
</div>
</div>
</div>
<div style="clear:both;font-size:0;">
</div>
</li>
You'll need:
function add() {
// Create elements
var d1 = c('div'), s1 = c('span'), ip = c('input'),
d2 = c('div'), s2 = c('span'), li = c('li'),
d3 = c('div'), s3 = c('span'), la = c('label'),
d4 = c('div');
// You can "chain" `appendChild`.
// `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
d1.appendChild(d2).appendChild(ip);
d2.appendChild(d3);
li.appendChild(d4);
setAttributes(
[li, d1, la, s2, s3, d2, ip, d3, d4],
[
{'class':"ie7fix", 'style':"width:620px;" },
{'class':"m_elementwrapper", 'style':"float:left;" },
{'class':"fieldlabel", 'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
{'class':"pspan arial", 'style':"text-align:right;font-size:14px;" },
{'class':"ispan", 'xml:space':"preserve" },
{'class':"m_elementwrapper", 'style':"float:left;width:475px;" },
{'class':"fieldcontent", 'type':"text", 'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
{'class':"fielderror" },
{'style':"clear:both;font-size:0;" }
]
);
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(li); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
var el = elements.length,
al = attributes.length;
if(el === al){
for(var n = 0; n < el; n++){
var e = elements[n],
a = attributes[n];
for(var key in a){
e.setAttribute(key, a[key]);
}
}
}else{
console.error("Elements length " + el + " does not match Attributes length " + al);
}
}
// Alias for shorter code.
function c(type){
return document.createElement(type);
};
use jquery library
<html>
<head>
<script src='jquery.js' type="text/javascript"></script>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
var div_content=$('#y').append(tag);
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>
I've got round this before by reading all of the values into an array before replacing the innerHTML and then writing them back again afterwards. This way you can write whatever you like into the div. Following works on all browsers that I have tried:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add() {
if(i>0) {
values=new Array();
for(z=0;z<i;z++) {
values.push(document.getElementById(z).value);
}
}
var tag = '<input type="text" name="' + i + '" id="' + i + '" /> <br/>';
document.getElementById("y").innerHTML += tag;
if(i>0) {
for(z=0;z<i;z++) {
document.getElementById(z).value=values[z];
}
}
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>

Categories

Resources