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.
Related
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>
I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}
Problem
I'm trying to using twitter intent to tweet out a pre-written, custom tweet. But when I click fa-twitter the box appears blank. I think the problem may be how I'm encoding the URL?
scripts.js
function shareTeam(){
$(".fa-twitter").click(function(){
// Create an empty array
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
// console.log(lastNames);
// var regularNames = lastNames.slice(0, 3); // Same as below, but no shuffling
var regularNames = lastNames;
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
regularName4 = regularNames[3]; // Defenseman
regularName5 = regularNames[4]; // Defenseman
regularName6 = regularNames[5]; // Goalie
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
// This is zero-indexed? So the numbers will be one lower than the actual teaser #
var teaser = "teaser";
var rand = Math.floor(Math.random() * 6);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?";
var twitterUsername = "#stltoday";
var interactiveURL = "http://staging.stltoday.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your own all-team #STLBlues team: ";
var teaser2 = "My #STLBlues dream team has " + regularName3 + " and " + regularName4 + ". Build your own: ";
var teaser3 = "My #STLBlues dream team has " + regularName4 + " and " + regularName5 + ". Build your own: ";
var teaser4 = "My #STLBlues team will skate circles around yours! Pick your team: ";
var teaser5 = regularName6 + " with the glove save! ";
var teaser6 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice: ";
// Push teasers into array
teasers.push(teaser1);
teasers.push(teaser2);
teasers.push(teaser3);
teasers.push(teaser4);
teasers.push(teaser5);
teasers.push(teaser6);
// This is the full url that will be switched in and out
var fullURL = "text="+teasers[rand]+"&url="+interactiveURL+"&via=("+twitterUsername+")";
// var fullURL = interactiveURL+"&via="+twitterUsername+"&text="+teasers[rand];
console.log(fullURL);
// It needs to be encoded properly as well
var encodedURL = baseURI+encodeURIComponent(fullURL);
// Change the href to the link every time the Twitter button is clicked
$(".link--twitter").attr("href", encodedURL);
console.log(encodedURL);
// if (lastNames.length === 6) {
// } else {
// var encodedURLGeneric = baseURI+encodeURIComponent(fullURL);
// $(".link--twitter").attr("href", encodedURLGeneric);
// }
});
}
The solution was to encode each part individually
function shareTeam(){
$(".fa-twitter").click(function(){
// Create an empty array
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
var regularNames = lastNames.slice(0, 4); // Same as below, but no shuffling
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
regularName4 = regularNames[3]; // Defenseman
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
// This is zero-indexed? So the numbers will be one lower than the actual teaser #
var teaser = "teaser";
var rand = Math.floor(Math.random() * 3);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?text=";
var twitterUsername = "stltoday";
var interactiveURL = "http://staging.stltoday.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your #STLBlues team:";
var teaser2 = "My #STLBlues dream team has " + regularName3 + " and " + regularName4 + ". Build your own:";
var teaser3 = regularName4 + " to " + regularName3 + " back to " + regularName2 + " — GOAL! Create your #STLBlues team:";
var teaser4 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice:";
// Push teasers into array
teasers.push(teaser1);
teasers.push(teaser2);
teasers.push(teaser3);
teasers.push(teaser4);
// This is the full url that will be switched in and out
// It needs to be encoded properly as well
var fullURL = baseURI+encodeURIComponent(teasers[rand])+"&url="+encodeURIComponent(interactiveURL)+"&via="+encodeURIComponent(twitterUsername);
var genericURL = baseURI+encodeURIComponent(teasers[3])+"&url="+encodeURIComponent(interactiveURL)+"&via="+encodeURIComponent(twitterUsername);
console.log(fullURL);
console.log(genericURL);
// Change the href to the link every time the Twitter button is clicked
$(".link--twitter").attr("href", fullURL);
console.log(fullURL);
if (lastNames.length === 6) {
console.log("Yeah, yeah, yeah");
} else {
$(".link--twitter").attr("href", genericURL);
}
});
}
I have a function with this specific array in it.
var elementsArray = xmlDocument.documentElement.getElementsByTagName('track');
// console.log(elementsArray);
var arrayLength = elementsArray.length;
var output = "<table>";
for (var i=0; i < arrayLength; i++)
{
var title = elementsArray[i].getElementsByTagName('title')[0].firstChild.nodeValue;
var artist = elementsArray[i].getElementsByTagName('artist')[0].firstChild.nodeValue;
var length = elementsArray[i].getElementsByTagName('length')[0].firstChild.nodeValue;
var filename = elementsArray[i].getElementsByTagName('filename')[0].firstChild.nodeValue;
console.log(title + ' ' + artist + ' ' + length + ' ' + filename);
output += "<tr>";
output += ("<td onclick='songSelect(\"" + filename + "\")'>" + title + "</td><td>" + artist + "</td>");
output += "</tr>";
}
With this array how would i generate a previous and next button to move.
http://jsfiddle.net/xbesjknL/
Once could use a linked list or even the notion of C-like pointers that point at the prev/curr/next tracks. But alas this is Javascript and the client side is too processing burdened.
So you could just build your own simplified idea of pointers in a cursor like object that is constantly pointing at the current track's index, the previous track's index and the next. And you'd call the refresh method everytime the user clicks the prev or next buttons to update the cursor's pointers accordingly.
var cursor = {
prev:(elementsArray.length-1),
curr:0,
next:(1 % (elementsArray.length-1)),
refresh: function(button){ //button is either the btnPrev or btnNext elements
if (button.getAttribute("id") === "btnPrev") {
old_curr = this.curr;
this.curr = this.prev;
if ((this.curr-1) < 0)
this.prev = elementsArray.length-1;
else
this.prev = this.curr - 1;
this.next = old_curr;
} else {
old_curr = this.curr;
this.curr = this.next;
if ((this.curr+1) > (elementsArray.length-1))
this.next= 0;
else
if (elementsArray.length === 1)
this.next = 0;
else
this.next = this.curr+1;
this.prev = old_curr;
}
}
};
// example usage:
cursor.refresh(btnPrev);
elementsArray[cursor.curr]; // gives the previous track, which is now the current track
You can even simplify this even more by just keeping track of only the current track. Note
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;
}
}