User input text box - javascript

I'm having a bit of trouble of getting the JavaScript code right. I need some help on what goes where and how it's supposed to look.
This is what I have so far in my script.
<script>
var i = "1";
var listItem = "";
function processInput() {
if (i <= 5) //Comparison operator//
document.getElementById("listItem").innerHTML = (i <= 5);
</script>
Here is my question:
Create a function called processInput(). Within the function create an if statement that runs if the value of i is less than or equal to 5. The if statement should perform the following actions:
Set the value of the listItem variable to the string "item" concatenated with the value of i.
Set the content of the element with an id equal to listItem to the value of the element with the id or toolbox.
Set the value of the element with the id of toolbox to an empty
string.
I'm not sure if I'm setting this up right. I have tried w3Schools and the information on their site seemed to be unhelpful/unclear.

Going step by step:
Set the value of the listItem variable to the string "item" concatenated with the value of i.
var listItem = "item" + i; // + performs string concatenation
Set the content of the element with an id equal to listItem to the value of the element with the id of toolbox.
document.getElementById(listItem.innerHTML = document.getElementById("toolbox").value;
Set the value of the element with the id of toolbox to an empty string.
document.getElementById("toolbox").value = "";
So the whole function should look like:
function processInput() {
if (i <= 5) {
var listItem = "item" + i;
document.getElementById(listItem.innerHTML = document.getElementById("toolbox").value;
document.getElementById("toolbox").value = "";
}
}

I don't know what's your goal behind this but that's how it's done.
remember that "i" will stay the same because you're not incrementing it
just study more javascript and i hope this helps you buddy
<script type="text/javascript">
var i = 1;
var listItem = "";
var listItemElement = document.getElementById("listItem");
var toolbox = document.getElementById("toolbox");
processInput();
function processInput() {
if (i <= 5) {
listItem = "item " + i;
listItemElement.innerHTML = toolbox.innerHTML;
toolbox.innerHTML = "";
}
}

Related

Different onclicks for different elements when adding new elements using Javascript

I am working on a project where the user decides how many buttons are there, and then each button triggers a different function.
What I have done is: I have an input that asks "Enter the number of buttons" and a "Submit" button. When the "Submit" button is clicked, the value of variable n is set to the user-defined value.
I then have the following code (assuming the user has set n to 10):
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
x.onclick = function() {alert(i)};
document.body.appendChild(x);
}
What I want is, that when div with id i is clicked, the pop-up message says i. But what has ended up happening is, that no matter which div I click, the pop-up message always says 10.
Why is this happening? How to fix this?
The only thing you need to change is the assignment of i inside the for-loop. Use let to define a locally-scoped variable. Also, use textContent instead of innerHTML for simple text. It is recommended to used const/let rather than var.
for (let i = 0; i < 10; i++) {
const x = document.createElement('div');
x.id = i;
x.textContent = i;
x.onclick = function() { alert(i) };
document.body.appendChild(x);
}
By iterating over your NodeList elements, you can take this next approach.
First of all, append all your created divs in your HTML and continue by looping through the elements list by document.querySelectorAll("div")
That way you select all elements and then assign an addEventListener to each one of the items. On your alert function, print this.id and it will return you the number of the id of the element which corresponds to your i index.
It would be the same also if you just put the whole addEventListener function inside the other loop.
I just separated both so you can understand it better.
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
document.body.appendChild(x);
}
let divs = document.querySelectorAll("div");
for(var a= 0; a < divs.length; a++){
divs[a].addEventListener("click", function(){
alert(this.id);
});
}
You can use getAttribute to read the id of the elements. I show you an example:
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
x.onclick = function(e) {
let dataId= e.currentTarget.getAttribute("id")
alert(dataId)
};
document.body.appendChild(x);
}
Explanation:
getAtrribute() returns the value of an html attribute as a string, just enter the name of the attribute in braces to get the value. In this case I entered "id" which is the value we want to retrieve.
Also to get the value of the element where you click I use currentTarget, to accurately retrieve the value of the div that the iteration creates. If you use target, and inside the div you have more elements, this code will generate an error. Therefore, it is important to use currentTarget for this application.
This happen because after the initialisationn the function will look for the value of i which is always 10 (once it has been initialized)
EDIT
As explained by #Mr. Polywhirl in his better answer, you can use let in your for loop to declare your variable locally instead of globally.
To solve your problem you can pass an event to the function (the click event) and the getting your value.
It can be done with either :
The value of the content (as you did with x.innerHTML)
Adding an id to the div and getting this id
Example :
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
x.onclick = function(event) {
alert(event.target.innerHTML) // with the content
alert(event.target.id) // with the id
};
document.body.appendChild(x);
}

JavaScript loop through JSON data and print in html

I'm new to JavaScript and I'm trying to figure out how-to loop through JSON and print each selected value in HTML. My solution below does everything I want except print "all" rows of the JSON data. It only prints the last one. I've been researching on StackOverflow and elsewhere, but I'm not finding the solution. Sorry if this is a redundant question and thank you for your help!
//Fetch JSON from URL
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
//https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
var index;
var obj = JSON.parse(songData);
for (index = 0; index < obj.length; ++index) {
var student_name = obj[index]['name'];
var student_email = obj[index]['email'];
var song_name = obj[index]['song'];
var song_url = obj[index]['url'];
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
}
});
Inside your for loop you are reassigning your elements' content in every Iteration. It means that you fill your elements with the First item of the Array on the First time you run the for, but the Second time you run It, you replace the elements' content with the Second item of the Array. So you get only the Last Item Data.
To solve this problema, you should "increment" your element's content on each Iteration, instead of replace it. To achieve that, you replace the Lines like
document.getElementById("studentName").innerHTML = '<br>'+student_name;
With
document.getElementById("studentName").innerHTML += '<br>'+student_name;
The += operator does a concatenation on strings
Becasue you set string for elements, don't add string.
Replace from:
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
To:
document.getElementById("studentName").innerHTML += '<br>'+student_name;
document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
document.getElementById("songTitle").innerHTML += '<br>'+song_name;
document.getElementById("songURL").innerHTML += '<br>'+song_url;

Trying to add get each listen item to log a unique number

I have created a list using a for loop and want to add an event listener to each of them, so that when each item is clicked, it's logged in the console the item number (e.g. if list item 1 is clicked, console log returns the variable currentNumber as 0).
However, with my current code, all I'm getting in the console log is "4". Can someone please help me with this? Thank you.
for (i = 0; i < tipsCatalog.length; i++) {
var newCategory = document.createElement('li');
newCategory.id = "sMonTipHeadline-" + [i];
newCategory.className = "sMonTipHeadline";
newCategory.innerHTML = tipsCatalog[i].tipHeadline;
catalogContainer.appendChild(newCategory);
}
var currentNumber = [];
for (i = 0; i < tipsCatalog.length; i++) {
currentNumber[i] = i;
tipsCatalogList[i].addEventListener('click', function() {console.log(currentNumber[i])});
}
I would try to add the number inside an element's attribute and then take it from there when you need it.
tipsCatalogList[i].addEventListener('click', function() {console.log($(this).attr('yournumber'))});

Using Javascript to dynamically create dom elements with incrementing ID's

I have a div with an ID "orangeButton" and each time you click on it it creates a new div. This works fine but... I want each newly created div to have an incremental number added to it's ID.
I am not sure how to do this.
Here is a fiddle of the code I have thus far with comments.
http://jsfiddle.net/taoist/yPrab/1/
Thank you
Javascript Code
var applicationArea = document.getElementById("applicationArea");
var orangeButton = document.getElementById("orangeButton");
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy'; // I want each newly created div to have a numeric value concatenated to it's ID. IE newDivThingy1 newDivThingy2 newDivThingy3
applicationArea.appendChild(newDivThingy);
};​
Am I missing something, why not use a counter?
var counter = 0;
button.onclick = function(){
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy' + (++counter);
// continue your stuff here
}
Libraries like underscorejs provide a uniqueid function for this. Otherwise its easy to implement one.
myNamespace.uniqueId = (function () {
var counter = 0; // in closure
return function (prefix) {
counter++;
return (prefix || '') + '-' + counter;
};
}());
Usage.
newDiv.id = myNamespace.uniqueId('newDiv');
Simply use a integer and increment it as each element is added.
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),
counter = 1;
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = "newDivThingy" + counter++;
applicationArea.appendChild(newDivThingy);
}
I have no doubt you have solution and may have forgotten this post.
BUT, I wold like to show a solution that is a compact format.
Note the counter is set to (counter++) so it will start at 1.
var orangeButton = document.getElementById("orangeButton");
var counter = 0;
orangeButton.onclick = function() {
document.getElementById('applicationArea')
.appendChild(document.createElement('div'))
.setAttribute("id", 'newDivThingy' + counter++);
// I want each newly created div to have a
// numeric value concatenated to it's ID.
// IE newDivThingy1 newDivThingy2 newDivThingy3
};​

How can I add additional elements to my array?

I was trying to get the country name and put it in the temparray, so that I can use the temparray to check the country (line 14). The problem is temparray can only contain one value and upon increasing the array length size by using temparray.length = 4, the heat map won't show up in the page.
The code below is to check duplicate name entry from within the array. If the country name is repeated, it will add the past value and its current value and add it into the data table again as the old row.
var i;
var suq = 0;
var temparray = [""];
var rowcount= 0;
//set the value
for (i = 0; i<count; i++){
var countryname = countryarray[i];
var hostcount = hosthitcount[i];
//document.write("hello");
for (rowcount=0;rowcount<temparray.length;rowcount++){
//check for any repeated country name
if (temparray[rowcount] != countryname){
data.setValue(suq, 0, countryname);
data.setValue(suq, 1, hostcount);
temparray[rowcount] = countryname;
//document.write("win");document.write("<br/>");
suq++;
}else{
//get the hits //rowindex
var pastvalue = data.getValue(rowcount,1);
//add the previous value with current value
var value = parseInt(hostcount)+parseInt(pastvalue);
value+= "";
//document.write(value);
//put it in the table
data.setValue(rowcount,1,value);
// document.write("lose");document.write("<br/>");
}
}
}
I don't really understand what you are trying to do with temparray. It can surely contain more than one element with a temparray.push(countryname). Maybe this JavaScript array reference will help you?

Categories