Getting Data out of a container - javascript

I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Guest " + (i+1)));
var input = document.createElement("input");
input.id = "Guest" + i;
container.appendChild(input);
container.appendChild(document.createElement("br"));
console.log(i.value);
It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.
function sendInput ()
{
var guestNames = document.getElementById("Guest").value
var personName = document.getElementById("people").value;
var eventType = document.getElementById("event").value;
var date = document.getElementById("date").value;
var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
document.getElementById('output').innerHTML = output.repeat(i);
}
The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.

IDs are difficult to work with in a dynamic environment, classes are generally the simplest solution. This code will convert your inputs to have classes, then loop through them and collect the names.
So change:
input.id = "Guest" + i;
to
input.setAttribute("class","guest");
And change
var guestNames = document.getElementById("Guest").value
to:
var guests = document.querySelectorAll(".guest");
var guestNames = [];
guests.forEach(function(el){
guestNames.push(el.value);
});
guestNames = guestNames.join(",");
If you are wanting a message for EACH guest, then you would use the below function:
function sendInput ()
{
var personName = document.getElementById("people").value;
var eventType = document.getElementById("event").value;
var date = document.getElementById("date").value;
var guests = document.querySelectorAll(".guest");
var guestNames = [];
document.getElementById('output').innerHTML = "";
guests.forEach(function(el){
document.getElementById('output').innerHTML += "Dear " + el.value + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
});
}

You try to get node by id var guestNames = document.getElementById("Guest").value
But all nodes have a different id, like a Guest0,Guest1 etc. I am trying to write my own code, but your snippet isn't full. I hope I helped you.

As far as I can see, when you try to fetch the guest name
var guestNames = document.getElementById("Guest").value
you won't get any element for two reasons because there's no element with id "Guest". In fact you generate them in the form "GuestN"
`input.id = "Guest" + i;`
You probably want to add a parameter i to sendInput () function, so that internally you can concatenate it to Guest as you did above and get the correct element with getElementById().

Your code is incomplete (as far as I can tell).
You do not specify the following elements anywhere:
'container', 'guest', 'people', 'event', 'data' or 'output'
I assume they should be defined somewhere in the HTML section (not provided)
To be able to create the variable displays, you need to define the 'container' you wish to initialize it before it is used in the for() loop that follows.
Example: var container = document.getElementById('container');
Within the loop, console.log(i.value) is invalid as i is not an element that has been assigne a value to display. It is a counter of the for() loop.
The function of sendInput(), I assume, is to collect the information from the user for each "Guest#" created by the first loop of your code. However you try to collect from "Guest" which has not been defined. For a number of 5, the collections should be for "Guest1", "Guest2", "Guest3", "Guest4", "Guest5". "Guest" only can not be found anywhere in your loop creation. Same goes for 'people, 'event' and 'date' which are referenced for value collection, but there are no elements named as such.
Not exactly sure why you are mixing DOM creation techniques (???).
You create the number of element for the guest, but then output the results with .innerHTML. You should use the DOM creation method, but I have used your code as you indicated you are a beginner.
Here is some (partially) corrected code that you can continue on with.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- link rel="stylesheet" href="common.css" media="screen" -->
<style>
</style>
</head><body>
<input type="text" value="5/28/2020" id="date">
<pre id='container'></pre>
<button id="report">Report</button>
<pre id='output'></pre>
<script>
console.clear();
function init() {
var number = 5;
var container = document.getElementById('container');
for (i=0;i<number;i++) {
var value = "Guest " + (i+1)+' ';
container.appendChild(document.createTextNode(value));
var input = document.createElement("input");
input.id = "Guest" + i;
input.value = value;
container.appendChild(input);
container.appendChild(document.createElement("br"));
console.log(i); // .value);
}
document.getElementById('report').addEventListener('click',sendInput);
} init();
function sendInput () {
var date = document.getElementById("date").value,
output = document.getElementById('output'),
info = '';
var guestNames = [...document.querySelectorAll('#container input')]; // alert(guestNames.length);
for (let i=0; i<guestNames.length; i++) {
info = `Dear ${guestNames[i].value}:\nYou have been invited to XXX's EVENT on ${date}\nThank you for coming!!\n\n`;
output.innerHTML += info;
}
// var guestNames = document.getElementById("Guest").value
// var personName = document.getElementById("people").value;
// var eventType = document.getElementById("event").value;
// var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
// output = `Dear ${guestNames}:\nYou have been invided to XXX's EVENT on ${date}\nThank you for coming!!`;
// document.getElementById('output').innerHTML = output.repeat(i);
}
</script>
</body></html>

Related

I'm not sure how to use lodash orderBy

My program is currently supposed to take the HTML input, put it into an object array, sort it using orderBy, then output it to the p2 textContent. I tested all of the aspects of this program before adding orderBy, and then the program stopped working.
var p1 = document.getElementById("p1");
var p2 = document.getElementById("p2");
var enterName = document.getElementById("name");
var enterRating = document.getElementById("rating");
var button = document.getElementById("button");
var players = [];
button.addEventListener("click", addPlayer);
function addPlayer() {
p1.innerText += enterName.value + " - " + enterRating.value + " " + "| ";
players.push({ player: enterName.value, rating: enterRating.value });
var sortedPlayers = _.orderBy(players, [rating, player], [desc, desc]);
console.log(players);
console.log(sortedPlayers);
p2.innerText = "";
for (i = 0; i < players.length; i++) {
p2.innerText += players[i].player + " - " + players[i].rating + " | ";
}
}
p1 exists and is used for testing purposes, just to make sure that my browser isn't lagging. After I added the orderBy, neither array logged to the console. Before, the players array logged with every run of the addPlayer() function.
I'm using codepen to write this program, and I am pretty sure lodash is installed if that is relevant.

No input text value via JavaScript DOM

I use JavaScript to create input text fields. And everything works fine, except attribute value. It simply doesn't generate and I don't know why?
Here's my code:
k=1;
function addtxt() {
var tip = document.createElement("input");
tip.type = "text";
tip.name = "tip[" + k + "]";
tip.value = "Question1";
var div = document.createElement("div");
div.innerHTML = "Question: " + tip.outerHTML + "<br />";
document.getElementById("mydiv").appendChild(div);
k++
}
This is what I got:
<input type="text" name="tip[1]">
may be try using setAttribute(), like, change:
tip.value = "Question1";
to
tip.setAttribute('value', "Question1");

append custom attribute to a dynamically created node javascript

I need to set the attribute of a node that I created through Javascript. However, it's becoming quite complicated because of where values are located in different functions throughout the script.
I have a constructor function:
function Todo(id, task, who, dueDate) {
this.id = id;
this.task = task;
this.who = who;
this.dueDate = dueDate;
this.done = false;
}
Then I create span elements which hold the todos:
function createNewTodo(todoItem) {
var li = document.createElement("li");
li.setAttribute("id", todoItem.id);
var spanTodo = document.createElement("span");
spanTodo.innerHTML =
todoItem.who + " needs to " + todoItem.task + " by " + todoItem.dueDate;
li.appendChild(spanTodo);
return li;
}
Then I get values from a form on the page which I use to set who, and task. And date, but that's a bit more complicated as I end up taking that value later in my code to get the difference between today's date and the date they entered.
function getFormData() {
var task = document.getElementById("task").value;
if (checkInputText(task, "Please enter a task")) return;
var who = document.getElementById("who").value;
if (checkInputText(who, "Please enter a person to do the task")) return;
var adate = document.getElementById("dueDate").value;
var reString = new RegExp("[0-9]{4}\\-\[0-9]{2}\\-\[0-9]{2}");
var date = compareDates(date);
var id = (new Date()).getTime();
var todoItem = new Todo(id, task, who, date);
todos.push(todoItem);
addTodoToPage(todoItem);
saveTodoItem(todoItem);
}
So, days is the value that I want here. I want to set dueDate to equal days so that I can use that value up in the innerHTML of the createNewToDo function.
function compareDates(date) {
var days = Math.floor(daysCal);
console.log(date);
todoItem.setAttribute("dueDate", days);
if (cdate < date) {
console.log("you have" + " " + days + " " + "more day(s)");
}
else if (cdate > date ) {
console.log("you are" + " " + -days + " " + "day(s) overdue");
}
}
Any ideas on modifications to set dueDate to the value of days?
Your todoItem is a JS object created by the Todo constructor, not a DOM node like li or spanTodo. Therefore, it has no setAttribute method, and if you want to set a property of it just assign to it (using a member operator):
todoItem.dueDate = daysL

Fetching results from LinkedIn API through javascript

First of all thank you for reading this. I am having some trouble fetching the data given by the Linkedin sign-in API with javascript. Here is the script:
<script type="text/javascript">
function onLinkedInAuth() {
IN.API.Profile("me").fields(["firstName","lastName","headline","summary","location","educations","skills"]).result(displayProfiles);
}
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("name").value = member.firstName +" "+ member.lastName;
document.getElementById("pos").value = member.headline;
document.getElementById("city").value = member.location.name;
document.getElementById("sum").value = member.summary;
var i=0;
do {
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.educations.values[i].schoolName + "</td></tr>";
document.getElementById('para').innerHTML = newHTML;
i++;
}
while(i<=1);
var v=0;
do {
var oldHTML = document.getElementById('tara').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.skills.values[v].skill.name + "</td></tr>";
document.getElementById('tara').innerHTML = newHTML;
v++;
}
while(member.skills.values[v].skill.name);
document.getElementById("educ").value = member.educations.values[1].schoolName;
document.getElementById("skills").value = member.skills.values[0].skill.name;
}
</script>
It's a very basic script to get the user infos and, among it, the educational and professional background of the user. The thing is that member.educations.values[i].schoolName and member.skills.values[v].skill.name can have multiple values and I want to gather them all.
It works as long as the specified fields are not empty but then it outputs an error saying that member.skills.values[v] is undefined and it does not run the second loop.
I know the error is really basic but I'm not that great in javascript.
Thanks for your help anyways, have a good day!
You should check the length of the returned values and then loop through them as needed. Something along the lines of:
var educations = member.educations;
if(educations._total > 0) {
for(var i = 0; i < educations._total; i++) {
document.getElementById("educ").value += (i > 0) ? ', ' : '';
document.getElementById("educ").value += educations.values[i].schoolName;
}
}

Using HTML5 localstorage to update some text without document.write

I have a div with a class of 'card', which is also draggable() with jQuery. I'm using localstorage to store an array containing information about the card.
var cardID = 1;
var cardValues = new Array();
var name = "Shifting Sliver";
var cost = "3U";
var text = "Sliver cannot be blocked except by slivers.";
var power = "2";
var toughness = "2";
cardValues.push(name);
cardValues.push(cost);
cardValues.push(text);
cardValues.push(power);
cardValues.push(toughness);
localStorage.setItem(cardID, cardValues.join(";"));
var cardKey = localStorage.key(0);
var getCardValues = localStorage.getItem(cardKey);
values = getCardValues.split(";");
var name = values[0];
var cost = values[1];
var text = values[2];
var power = values[3];
var toughness = values[4];
function writeCard()
{
document.write('Card Name: ' + name + '<br />');
document.write('Card Cost: ' + cost + '<br />');
document.write('Card Text: ' + text + '<br />');
document.write('Card Power: ' + power + '<br />');
document.write('Card Toughness: ' + toughness);
}
In the html:
<div class="card">
<div class="info"><script type='text/javascript'> writeCard(); </script></div>
</div>
After dragging the card, when releasing the mouse, document.write causes the whole page to refresh and only the data in document.write is shown. How can I insert the data onto the card without using document.write?
I think I need to use DOM manipulation, but I'm a bit stuck on exactly how.
You can not use document.write when document is completed loading use innerHTML instead
ypu can also use jQuery .append

Categories