How can I fill an empty JavaScript array? - javascript

I've looked all over online for something that could aid me to fill an empty array with given values the user inputs from a text box that will get stored inside an array.
So far I have the following code:
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
var x = [];
x.push(text);
console.log(x);
When I input something in the textbox and see what happens in the console it tends to replace the previous value that was sent there first.
For example, if I wrote "Hello", this will get sent into the array so it'll be seen as:
["Hello"]
But if I type in something again, hoping that the result will continue to store the data being inputted inside, it does this:
*Writes down "Hi" in the text box:
["Hi"]
I want the result to be something like this:
["Hello", "Hi"]
I am aware my code does need tweaking and I am doing something wrong which is causing that result, but I can't seem to figure it out.
I'm looking for an answer in vanilla JavaScript.
Thank you.

The problem is you are redeclaring variable x and initializing it with an empty array, every time when you run that code. Make the x a global variable by moving it out of the current function or block
var x = [];
Another Block
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
x.push(text);
console.log(x);

var x = [];
function() {
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
x.push(text);
console.log(x);
}
something like this should fix your problem. You were declaring x as an empty array every time you ran your javascript which would reset it to an empty arry.

Related

Make javascript as function

i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/

What is the purpose of += sign to this code, when you can just do + instead?

I've been watching a javascript tutorial to refresh my knowledge of it.
I just need some guidance on why he decided to use this code "style"
Basically, there's a variable named result with an empty string ("") and I'm not so sure why he used (result += ...) when he can also use (result = ...) where it showed the same output when I tried.
function mySentence(myName, myVerb){
var result = "";
result += myName + " " + myVerb + " towards the tree.";
return result;
}
console.log(mySentence("Dale", "walked"));
vs
function mySentence(myName, myVerb){
var result = "";
result = myName + " " + myVerb + " towards the tree.";
return result;
}
console.log(mySentence("Dale", "walked"));
Link of video: https://youtu.be/PkZNo7MFNFg
36:28:00 : Word Blanks
The only reason I can think of for having it there is that the author wanted to be able to rearrange a series of statements after the initial declaration that all used += without having to worry about which was the first statement originally. E.g.:
var result = "";
result += "something";
result += "another thing";
result += "yet another thing";
...where they may want later to swap things around:
var result = "";
result += "another thing";
result += "something";
result += "yet another thing";
The variable result is set to "", an empty string in the beginning.
When you do result= the variable will be replaced with the new value.
But when you do result+= the variable does not get replaced. It will be added with the value that already exists.
For example, in your code, if the variable is set to some value in the beginning, like result="The answer is: ", then the two styles would yield different results. The result= style will return Dale walked towards the tree.. And the result+= will return The answer is: Dale walked towards the tree.

How to document.write multiple variables at once?

I have a loop that will declare a new variable each time. I want to write my results to a new window and I would like every string declared to print with breaks.
I did try making combining all vars together with '+' signs (using [i] to get the number of occurrences) but document.write printed it because it was a string.
Does anyone know what I can do? I'm sure there must be a few ways but I've been stuck on this for a while.
window['question'+i] = "some stuff";
var myWindow = window.open("", "Questions", "width=500,height=600");
myWindow.document.write(
question0 + ("<br>") +
question1 + ("<br>") +
question2 + ("<br>") +
question3 + ("<br>")
...
)
I recommend to not use different variables. Array's are made for these kind of things and provide functions to do this a lot easier. See this snippet below how to store the texts from a loop in an array and easy print it splitted by a <br> using the join function.
var values = new Array();
for (var i = 0; i < 10; i++) {
values.push("<span>value " + i + "</span>");
}
document.getElementById('result').innerHTML = values.join("<br>");
//If you really want to use document.write()
//document.write(values.join("<br>"));
<div id="result"></div>

Use Variable as its name and not its content

I have a function that takes 2 inputs, the variable name as a string and the variable itself - it prints both via console.
var variable1 = ["entry1","entry2"];
function logthis(input1, input2){
console.log(input1+ "\n " + input2)
}
logthis("variable1", variable1) ;
I want to be able to use it as logthis(variable1); and get the same result.
How can I reference the variable name (as a string) and not its contents?
eg, console.log(input2.name) will not work
Something like the C+ equivalent of "nameOf(variable1)"
var variable1 = ["entry1","entry2"];
function logthis(input1, input2){
console.log(input1+ "\n " + input2)
}
logthis('variable1', variable1) ;
You are sending the reference. Pass first argument as string.
Try to get your input from the table first
function logthis(inputTable){
var input1 = inputTable[0];
var input2 = inputTable[1];
console.log(input1+ "\n " + input2) // will display "entry1 \n entry2 "
}
var table1 = ["entry1","entry2"];
logthis(table1);

Unexpected Number error

I have been writing a function to allow users to upload images from their local file system to a website using JavaScript. I have successfully been able to upload images to the browser.
I have also written a function to allow the user to delete these images.
var count = 0;
function getPhoto(){
var file = document.getElementById('ad_photo');
var list = document.getElementById('ad_photo_upload');
var fReader = new FileReader();
var photo_list = [];
var counter;
fReader.readAsDataURL(file.files[0]);
fReader.onloadend = function(event){
counter = count.toString();
list.innerHTML += "<li id = 'pic " + counter + "'><img src='" + event.target.result + "'></img><a class = 'close' onclick = 'rem_pic(pic " + counter + ")'>X</a></li>";
photo_list[count] = event.target.result;
count++;
}
}
function rem_pic(theID){
var element = document.getElementById(theID);
element.outerHTML = "";
delete element;
}
My issue is whenever I call the "rem_pic(theID)" function I get a Chrome Browser error message that says "Uncaught SyntaxError: Unexpected number". Does anyone have any clue to why this might be? And how I could possibly improve the functions I have written so they work correctly?
Thanks
This happens because you pass a number to your function:
'rem_pic(pic " + counter + ")'
will render to
'rem_pic(pic 1)'
^ or any other number according to your counter value
And this is wrong as javascript params can't contain spaces.
So you probably need to pass a string:
rem_pic(\"pic " + counter + "\")
Looking at your code seems like you use it's as HTML id attribute. id attribute can't contain space chars too so your code should be like
rem_pic(\"pic" + counter + "\")
if your id in layout has format id="pic1", id="pic2", etc.

Categories