need to append user data to array - javascript

my original question got answered but I realize that every time I try to push user data in the arrays it wouldn't allow me to do is there any another to append data to arrays or is the push method the only way. or should i create a new array................................................................
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
}
$("#name").focus();
};
// display scores
const displayScores = () => {
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea id="scores_display"></textarea>
</div>
</main>

All my previous notes were incorrect. Your adhoc $ const threw me off! My apologies.
The issue was you weren't calling displayScores() after updating the array. Plus, I added a line to that function to clear the existing text before looping through your data.
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
// add to the textarea
displayScores()
}
$("#name").focus();
};
// display scores
const displayScores = () => {
document.getElementById("scores_display").textContent = "";
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea rows="6" id="scores_display"></textarea>
</div>
</main>

Related

Form doesn't remove alert from the first input box when the input being an empty string is changed to false

I am doing an assignemnt for school to showcase our knowledge of javascript. It is doing everything I want it to except when I adjust the first input from an empty string to a value it still has the display of first name required. I was also wondering if anyone had insight as to how to display the needed inputs when the other buttons I have clicked are cliked as I don't want the other functions to run unless all inputs are filled in the form. Thanks!
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t2result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t1result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
you were getting wrong element in your function validate in first condition , in else condition you were getting t2result instead of t1, hope this will work now.

Getting an Uncaught TypeError: Cannot set property 'onclick' of null with <script> at the end

I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>

Displaying two values from two different arrays

I need to display the highest test score out of one array and the person who received that score from another array. Here is the code so far:
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var textDisplay;
var $ = function(id) {
return document.getElementById(id);
}
var listArray = function() {
$("results").value = "";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
}
}
var showBest = function() {
$("results").value = "";
$("results").value += "High Score = " + Math.max.apply(null, scores) + "\n";
$("results").value += "The highest scoring student is = " //here is where I need help
}
var addElement = function() {
$("results").value = "";
// get user entries
var name = $("name").value;
var score = parseInt($("score").value);
// check entries for validity
if (name == "" || isNaN(score) || score < 0 || score > 100) {
alert("You must enter a name and a valid score");
} else {
names[names.length] = $("name").value;
scores[scores.length] = parseInt($("score").value);
$("name").value = "";
$("score").value = "";
}
$("name").focus();
}
window.onload = function() {
$("list_array").onclick = listArray;
$("add").onclick = addElement;
$("show_best").onclick = showBest;
$("name").focus();
}
<section>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array"><br>
<h2>Results</h2>
<textarea id="results"> </textarea><br>
<input type="button" id="list_array" value="List Array"><br>
<input type="button" id="show_best" value="Show Best Score"><br>
</section>
Is there any way to combine the arrays so they associate with each other? Even then I wouldn't know how to display the student separately from the score. Ideally hitting the "show_best" button would show the highest score and the name of the student who received that score.
Try this:
var showBest = function() {
const max = Math.max.apply(null, scores);
$("results").value = "";
$("results").value += "High Score = " + max + "\n";
$("results").value += "The highest scoring student is = " + names[scores.indexOf(max)] //here is where I need help
}
This is a solution using your data structure:
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var textDisplay;
var $ = function(id) {
return document.getElementById(id);
}
var listArray = function() {
$("results").value = "";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
}
}
var showBest = function() {
$("results").value = "";
var max = Math.max.apply(null, scores);
$("results").value += "High Score = " + max + "\n";
$("results").value += "The highest scoring student is = " + names[scores.indexOf(max)];
}
var addElement = function() {
$("results").value = "";
// get user entries
var name = $("name").value;
var score = parseInt($("score").value);
// check entries for validity
if (name == "" || isNaN(score) || score < 0 || score > 100) {
alert("You must enter a name and a valid score");
} else {
names[names.length] = $("name").value;
scores[scores.length] = parseInt($("score").value);
$("name").value = "";
$("score").value = "";
}
$("name").focus();
}
window.onload = function() {
$("list_array").onclick = listArray;
$("add").onclick = addElement;
$("show_best").onclick = showBest;
$("name").focus();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Score Array</title>
<link rel="stylesheet" href="styles.css" />
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="test_scores.js"></script>
</head>
<body>
<section>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array"><br>
<h2>Results</h2>
<textarea id="results"> </textarea><br>
<input type="button" id="list_array" value="List Array"><br>
<input type="button" id="show_best" value="Show Best Score"><br>
</section>
</body>
</html>
I would advice you, as suggested in the comment, to pass to an object structure in the form:
{
name: "example"
score: 10
}
var testResults = [
{
name: "Ben",
score: 88
},{
name: "Joel",
score: 98
},{
name: "Judy",
score: 77
},{
name: "Anne",
score: 88
}
];
var textDisplay;
var $ = function(id) {
return document.getElementById(id);
}
var listArray = function() {
$("results").value = "";
for (var i = 0; i < testResults.length; i++) {
$("results").value += testResults[i].name + ", " + testResults[i].score + "\n";
}
}
var showBest = function() {
$("results").value = "";
var scores = testResults.map(function(res) { return res.score;});
var max = Math.max.apply(null, scores)
var name = testResults.filter(function(res) { return res.score === max;}).pop().name;
;
$("results").value += "High Score = " + max + "\n";
$("results").value += "The highest scoring student is = " + name;
}
var addElement = function() {
$("results").value = "";
// get user entries
var name = $("name").value;
var score = parseInt($("score").value);
// check entries for validity
if (name == "" || isNaN(score) || score < 0 || score > 100) {
alert("You must enter a name and a valid score");
} else {
testResults.push({
name: $("name").value,
score: parseInt($("score").value)
});
$("name").value = "";
$("score").value = "";
}
$("name").focus();
}
window.onload = function() {
$("list_array").onclick = listArray;
$("add").onclick = addElement;
$("show_best").onclick = showBest;
$("name").focus();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Score Array</title>
<link rel="stylesheet" href="styles.css" />
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="test_scores.js"></script>
</head>
<body>
<section>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array"><br>
<h2>Results</h2>
<textarea id="results"> </textarea><br>
<input type="button" id="list_array" value="List Array"><br>
<input type="button" id="show_best" value="Show Best Score"><br>
</section>
</body>
</html>
The following is an example of how to combine the two arrays and find the highest score student:
var scores = [
{name: "ben", score: 88},
{name: "Joel", score: 98},
{name: "Judy", score: 77},
{name: "Anne", score: 88}
];
var getHighScoreStudent = function(scores) {
return scores.reduce(function(acc, item) {
if (item.score > acc.score) {
return item;
} else {
return acc;
}
});
};
var ans = getHighScoreStudent(scores);
console.log(ans);

Adding an event listener to DOM elements pushed into an array

Apologies for the poorly-worded question. It's my first question here!
I am trying to make an application whereby one can log the scores of players from any game and see the results at the end of the game (see the code snippet below).
So far, I have managed to push players and their scores (initially empty arrays) into the main array and thereby presented these players in a list (see below):
HTML
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
JavaScript
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
This gives me a list with the players' names, inputs to enter scores and buttons to log the scores. So far, so good.
But...
I am just trying to get each button to work. As you can see above, I gave each submit button classes ("submitScoreBtn"). I'm at the stage where I want to make sure that my new buttons work. Here's my code so far:
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
for (var x = 0; x < submitScore.length; x++){
submitScore[x].addEventListener("click", () => {
alert("selected");
});
}
I initially was getting errors without adding a for loop. Now I don't get any errors, but I also don't get any alerts. I'm just not sure why these buttons do not work.
Please see the code snippet below.
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
for (var x = 0; x < submitScore.length; x++){
submitScore[x].addEventListener("click", () => {
alert("selected");
});
}
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
Being as you're dynamically creating the buttons, it might be easier to simply add the function to the button's onclick.
You can still access the event object from this click by sending it as a parameter, like:
<input type='submit' onclick='submitScoreClick(event)' class='submitScoreBtn'>
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' onclick='submitScoreClick(event)' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
function submitScoreClick (e) {
alert("selected");
};
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
At the point in time when this code is run:
for (var x = 0; x < players.length; x++){
submitScore[x].addEventListener("click", (event) => {
event.alert("selected");
});
}
players.length is equal to 0. So the code is essentially never executed.
remove the for loop and add this code
document.addEventListener('click', function (event) {
if ( event.target.classList.contains( 'submitScoreBtn' ) ) {
alert("selected");
}
}, false);
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push({
player: entered,
score: []
});
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i = 0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className = "each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
document.addEventListener('click', function(event) {
if (event.target.classList.contains('submitScoreBtn')) {
alert("selected");
}
}, false);
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
The easiest solution is to use variables and createElement just like you do with toAdd. This way each created entry will remember its own inputs (local variables to the function), and you can use for example the score input variable in the click handler without confusion of which number input belongs to which entry.
I removed the class for the inputs because it's not needed to select them anymore, but you can still add some for styling for example. If you want to add classes to select them all, be sure to run querySelectorAll each time, so that added elements are actually selected.
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
var addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
var createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " ";
var enterScore = document.createElement("input");
enterScore.type = 'number';
enterScore.placeholder = 'enter score';
var submitScore = document.createElement("input");
submitScore.type = 'submit';
submitScore.addEventListener("click", () => {
alert("selected score: " + enterScore.value);
});
newLi.appendChild(enterScore);
newLi.appendChild(submitScore);
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>

Save array of data

I have use jquery in adding new input type as long as the user want it.
#using (Html.BeginForm("addBatch_CARF", "CARF", FormMethod.Post, new { #name = "register" }))
{
#Html.ValidationSummary(true)
<div id="formAlert" class="alert alert-danger">
<a class="close">×</a>
<strong>Warning!</strong> Make sure all fields are filled and try again.
</div>
var catName = "";
var displayCan = "";
var candidates = "";
for (int i = 0; i < Model.Count; i++)
{
if (catName != Model[i].request_category)
{
<li class="list-group-item list-group-item-success">
#Html.DisplayFor(modelItem => Model[i].request_category)
<span class="pull-right" style="margin-right:60px;">Special Instructions</span>
</li>
catName = Model[i].request_category;
displayCan = catName;
}
if (displayCan == Model[i].request_category)
{
candidates = Model[i].request_name;
<div class="checkbox_request">
#Html.CheckBoxFor(model => model[i].isSelected, new { #class = "is_selected" })
#Html.DisplayFor(model => model[i].request_name)
#if(Model[i].request_name == "Folder Access")
{
<span class="label label-danger">Pls specify all the drive path. Note: For accessing of drives outside PETC please proceed to Online CARF</span>
}
<span class="pull-right">
#Html.EditorFor(model => model[i].special_instruction)
</span>
#Html.HiddenFor(model => model[i].request_type_id)
#Html.HiddenFor(model => model[i].system_roles_id)
</div>
}
}
<li class="list-group-item list-group-item-success">
Access to:
</li>
<div class="input_fields_wrap">
<button class="add_field_button btn btn-primary">Add More Fields</button>
<div>
<input type="text" name="fname[]" placeholder="First Name">
<input type="text" name="lname[]" placeholder="Last Name">
<input type="text" name="email_add[]" placeholder="Email Address">
<input type="text" name="user_id[]" placeholder="User ID">
</div>
</div>
<p class="request_btn">
<button type="submit" class="btn btn-primary" id="addbtn">Save</button>
</p>
}
Javascript
<script type="text/javascript">
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="fname[]" placeholder="First Name"/> <input type="text" name="lname[]" placeholder="Last Name"/> <input type="text" name="email_add[]" placeholder="Email Add"/> <input type="text" name="user_id[]" placeholder="User ID"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
</script>
How will I add this data to my database? I've tried this code in my controller but these following parameters have no values string[] fname= null, string[] lname= null, string[] email_add= null, string[] user_id = null.
[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list = null, string[] fname= null, string[] lname= null, string[] email_add= null, string[] user_id = null)
{
var data = db.Employees_All_vw.Where(x => x.NT_Name == #User.Identity.Name.Remove(0, 9).ToLower() && x.active_flag == true).FirstOrDefault();
//add data into CARF table
CARF carf = new CARF();
carf.requestor = data.Emp_Badge_No;
carf.carf_type = "BATCH CARF";
carf.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
carf.created_date = System.DateTime.Now;
carf.active_flag = true;
db.CARves.Add(carf);
db.SaveChanges();
int id = carf.carf_id;
//add data into Request Access Table
foreach (var i in list)
{
int val = 1;
bool y = Convert.ToBoolean(val);
if (i.isSelected == y)
{
Request_Access ra = new Request_Access();
ra.request_access_id = 1;
ra.carf_id = id;
ra.request_type_id = i.request_type_id;
ra.special_instruction = i.special_instruction;
ra.ra_assignee = i.system_roles_id;
ra.dept_approval = null;
ra.dept_approval_date = null;
ra.dept_remarks = null;
ra.final_approval = null;
ra.final_approval_date = null;
ra.final_remarks = null;
ra.acknowledge_by = null;
ra.acknowledge_date = null;
ra.journal = null;
ra.closed_by = null;
ra.closed_date = null;
ra.verified_by = null;
ra.verified_date = null;
db.Request_Access.Add(ra);
}
db.SaveChanges();
}
//add all list of names to the Batch CARF table
for (var x = 1; x < fname.Count(); x++)
{
//foreach(var x in fname)
Batch_CARF batch = new Batch_CARF();
batch.carf_id = id;
batch.fname = fname[x];
batch.lname = lname[x];
batch.email_add = email_add[x];
batch.user_id = user_id[x];
batch.active_flag = true;
db.Batch_CARF.Add(batch);
}
db.SaveChanges();
//send email notification to the data owner or final approver by batch
TempData["MessageAlert"] = "Successfully created!";
return RedirectToAction("Batch_CARF");
}

Categories