Custom id's in javascript created elements - javascript

So I am working on a jeopardy web app and I have a portion of the app where players can create as many teams as they need and give them a custom name.
HTML
<!--Score Boards-->
<div id="teamBoards">
<div id="teams">
</div>
<div id="addTeams">
<h3>Add Teams</h3>
<input type="text" placeholder="Enter Team Name" id="teamName">
<button id="addTeam">Add a Team</button>
</div>
</div>
JS
var div = document.createElement("div");
div.className = "Teams"
var teamNameElement = document.createElement("h3");
var teamName = $('#teamName').val();
teamNameElement.textContent = teamName;
var score = document.createElement("h4");
score.textContent = "0";
score.id = "score"+teamName;
score.className = "score";
var plusButton = document.createElement("button");
plusButton.textContent = "+";
plusButton.id = "plus"+teamName;
plusButton.className = "plus";
var minusButton = document.createElement("button");
minusButton.textContent = "-";
minusButton.id = "minus"+teamName;
minusButton.className = "minus";
div.appendChild(teamNameElement);
div.appendChild(score);
div.appendChild(plusButton);
div.appendChild(minusButton);
var placementDiv = document.getElementById('teams');
placementDiv.appendChild(div);
The code above creates a team name, a place for the score with 0 preset, and a plus and minus button for points.
I start to have trouble when I go to add or subtract points by 100.
JS
$(plusButton).on('click', add);
$(minusButton).on('click', minus);
function add(){
var score1 = $('.score').html();
console.log(score1);
score1 = Number(score1);
score1 = score1 + 100;
console.log(score1);
$(score).html(score1);
}
function minus(){
var score1 = $('.score').html();
score1 = Number(score1);
score1 = score1 - 100;
$(score).html(score1);
}
All of the code here is in one function, so some variables from the plus and minus functions could be the variables from the code above. The problem is that I can not add points to specific teams' scoreboard through a specific id for each team score.

Here is a way to do what your looking at using more jQuery and $this selectors to work with individual teams like you want. I added some notes in the snippet below. Just run the snippet a few times and look at the comments to see how the teams are being selected.
$(function(){
var teamCount = 0;
var $teamsDiv = $("#teams");
$("#addTeam").click(function(){
//get the team name value
var teamName = $("#teamName").val();
//Create clone of html team template
var $newTeam = $("#teamTemplate").clone();
//Set an id for each team using the teamCount var
$newTeam.attr("id", "team" + teamCount);
//Set the entered text
$newTeam.find(".teamName").text(teamName);
//Set the score to zero
$newTeam.find(".score").text("0");
//Append new team to teams div
$teamsDiv = $("#teams");
$teamsDiv.append($newTeam.html());
});
//Add button press (using $("#teams").on('click'... allows for setting
//listeners on dynamically created html
$("#teams").on('click', '.plusButton', function() {
var $teamTemplate = $(this).closest(".template");
var $score = $teamTemplate.find(".score");
var teamName = $teamTemplate.find(".teamName").text();
var currentScore = parseInt($score.text());
$score.text(currentScore + 100);
$(this).closest(".template").find(".teamName");
console.log(teamName + " Score: " + $score.text());
})
//Minus button press
$("#teams").on('click', '.minusButton', function() {
//Using the "this" selector edit just the div you want.
var $teamTemplate = $(this).closest(".template");
var $score = $teamTemplate.find(".score");
var teamName = $teamTemplate.find(".teamName").text();
var currentScore = parseInt($score.text());
//Set new score text
$score.text(currentScore - 100);
//Console.log just to see what is happening
$(this).closest(".template").find(".teamName");
console.log(teamName + " Score: " + $score.text());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Score Boards-->
<div id="teamBoards">
<div id="addTeams">
<h3>Add Teams</h3>
<input type="text" placeholder="Enter Team Name" id="teamName">
<button id="addTeam">Add a Team</button>
</div>
<br />
<div id="teams">
</div>
</div>
<div style="display:none;" id="teamTemplate" >
<div class="template">
<span class="teamName"></span>
<button class="plusButton" type="button">+</button>
<button class="minusButton">-</button>
<span class="score">0</span>
<br />
</div>
</div>
I would highly recommend the Jquery video tutorial for getting a jump on using jQuery. It is a great tutorial that shows all the tricks to making client side code quick and easy.

Related

How can I execute a function without an event?

Solved by # epascarello
Have to execute function without event so that discount can be displayed along with prices at the start without clicking or any other event
You can see in below snippet that 1st one is running automatic while 2nd one is running on click . Can it possible to run 2nd one as automatic because it solves my most of issues using this keyword
Let me know if you need clarification . Any suggestion or comments will be helpful.
function discount1() {
var sendTotal = document.getElementsByClassName("TotalPrice1")[0].innerHTML;
var send1 = sendTotal.replace(/₹/gi, "");
var send2 = send1.replace(/,/gi, "");
var send3 = Number(send2)
var send = document.getElementsByClassName("DiscPrice1")[0].innerHTML;
var send4 = send.replace(/₹/gi, "");
var send5 = send4.replace(/,/gi, "");
var send6 = Number(send5)
var rest = ((send3 - send6) / send3) * 100
document.getElementsByClassName("demo1")[0].innerHTML = rest.toFixed(0) + "% off";
}
discount1();
function discount(rest) {
var sendTotal = rest.parentElement.getElementsByClassName("TotalPrice")[0].innerHTML;
var send1 = sendTotal.replace(/₹/gi, "");
var send2 = send1.replace(/,/gi, "");
var send3 = Number(send2)
var send = rest.parentElement.getElementsByClassName("DiscPrice")[0].innerHTML;
var send4 = send.replace(/₹/gi, "");
var send5 = send4.replace(/,/gi, "");
var send6 = Number(send5)
var rent = ((send3 - send6) / send3) * 100
rest.getElementsByClassName("demo")[0].innerHTML = rent.toFixed(0) + "% off";
}
<div>
<div class="seen" onclick="discount1()">
<div class="TotalPrice1">₹9,728</div>
<div class="DiscPrice1">₹5,435</div>
<div class="demo1"></div>
</div>
</div>
<br>
<div>
<div class="seen" onclick="discount(this)">
<div class="TotalPrice">₹15,670</div>
<div class="DiscPrice">₹13,785</div>
<div class="demo"></div>
</div>
</div>
So you need to call your function with the element.
How you get the elements is up to you. querySelectorAll, getElementsByClassName, ids, etc.
function discount () { /*...*/ }
document.querySelectorAll(".daad").forEach(discount);
you can do it inside of the function
function discount () {
document.querySelectorAll(".daad").forEach(function (reed) {
var saadTotal = reed.parentElement.getElementsByClassName("Total")[0].innerHTML;
console.log('saadTotal', saadTotal);
var saadTotal2 = reed.querySelector(".Total").textContent;
console.log('saadTotal2', saadTotal2);
}
}
discount();
This is answer for previous question you can see in question edits
This is what I needed to do show discount percentage without any event (like onclick or onload) . You can see in below snippet .
function discount(rest) {
var sendTotal = rest.parentElement.getElementsByClassName("TotalPrice")[0].innerHTML;
var send1 = sendTotal.replace(/₹/gi, "");
var send2 = send1.replace(/,/gi, "");
var send3 = Number(send2)
var send = rest.parentElement.getElementsByClassName("DiscPrice")[0].innerHTML;
var send4 = send.replace(/₹/gi, "");
var send5 = send4.replace(/,/gi, "");
var send6 = Number(send5)
var rent = ((send3 - send6) / send3) * 100
rest.getElementsByClassName("demo")[0].innerHTML = rent.toFixed(0) + "% off";
}
document.querySelectorAll(".seen").forEach(discount);;
<div>
<div class="seen" onclick="discount(this)">
<div class="TotalPrice">₹9,728</div>
<div class="DiscPrice">₹5,435</div>
<div class="demo"></div>
</div>
</div>
<br>
<div>
<div class="seen" onclick="discount(this)">
<div class="TotalPrice">₹15,670</div>
<div class="DiscPrice">₹13,785</div>
<div class="demo"></div>
</div>
</div>

How to access form values with variable names?

I have made a script that produces a form in a Google spreadsheet, takes its input values and appends them to the current sheet. All this works perfectly fine until I try and access the input values that have variable names.
I'm currently focusing on trying to get the inputs entered into the "Price" fields of which i are created with names "vPrice" + (i + 1) where i is the number entered previously in "Number of Variations" numVar.
In varItemAdd() I can access the values individually (vPrice1, vPrice2 etc.) and they produce the correct values. I can also access the numVar value but when I try to incrementally adjust the vPrice variable to produce each value on the spreadsheet it comes up as 'undefined'.
Script:
function varItemAdd(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var number = form.numVar;
var attribNumber = form.numAttr;
sheet.appendRow([form.manufacturer, number, attribNumber]);
for (i=0;i<number;i++) {
var vPrice = "vPrice" + (i + 1);
var vPriceInput = form.vPrice;
sheet.appendRow([vPriceInput, number, attribNumber]);
}
return true;
}
HTML
<body>
<form>
<!-- Select Number of Attributes to appear -->
<h2 class="title">Number of Attributes:</h2>
<input class="input-box" type="number" min="1" max="5" id="numAttr" name="numAttr" value="1"><br/>
<!-- Select Number of Variations to appear -->
<h2 class="title">Number of Variations:</h2>
<input class="input-box" type="number" id="numVar" name="numVar" value="1"><br/>
<h3 class="buttons" id="submit" onclick="addFields()">ADD</h3>
<div id="attBoxes"></div>
<div id="varBoxes"></div>
<br>
<input class="buttons" id="submit" type="button" value="SUBMIT"
onclick="google.script.run
//.withSuccessHandler(google.script.host.close)
.varItemAdd(this.parentNode)" />
<input class="buttons" id="reset" type="reset" value="RESET">
</form>
</body>
<script type='text/javascript'>
function addFields(){
// Get number of variation inputs to create
var number = document.getElementById("numVar").value;
// Get number of attribute inputs to create
var attribNumber = document.getElementById("numAttr").value;
// Get container <div>s where dynamic content will be placed
var varBoxes = document.getElementById("varBoxes");
var attBoxes = document.getElementById("attBoxes");
// Clear previous contents of the container
while (varBoxes.hasChildNodes()) {
varBoxes.removeChild(varBoxes.lastChild);
}
while (attBoxes.hasChildNodes()) {
attBoxes.removeChild(attBoxes.lastChild);
}
attBoxes.appendChild(document.createTextNode("Attribute Name(s)"));
// For each attribute append an input box inside each variation
for (k=0;k<attribNumber;k++){
var attTitle = attBoxes.appendChild(document.createElement("h2"));
var attInput = attBoxes.appendChild(document.createElement("input"));
attTitle.textContent = "Attribute " + (k + 1);
attInput.type = "text";
attInput.name = "v-att" + (k + 1);
attBoxes.appendChild(document.createElement("br"));
};
attBoxes.appendChild(document.createElement("br"));
// For each variation create inputs
for (i=0;i<number;i++){
varBoxes.appendChild(document.createTextNode("Variation " + (i+1)));
// Set variables
var skuTitle = varBoxes.appendChild(document.createElement("h2"));
var skuInput = document.createElement("input");
var priceTitle = varBoxes.appendChild(document.createElement("h2"));
var priceInput = document.createElement("input");
var attributes = varBoxes.appendChild(document.createElement("div"));
attributes.id = "varAttribs";
var varAttribs = document.getElementById("varAttribs");
// Set element values
skuTitle.textContent = "SKU";
skuInput.type = "text";
skuInput.name = "vSku";
priceTitle.textContent = "Price";
priceInput.type = "number";
priceInput.id = "vPrice" + (i + 1);
priceInput.name = "vPrice" + (i + 1);
// Call elements
varBoxes.appendChild(skuTitle);
varBoxes.appendChild(skuInput);
varBoxes.appendChild(document.createElement("br"));
varBoxes.appendChild(priceTitle);
varBoxes.appendChild(priceInput);
varBoxes.appendChild(document.createElement("br"));
for (j=0;j<attribNumber;j++){
var aValueTitle = varAttribs.appendChild(document.createElement("h2"));
var aValueInput = document.createElement("input");
aValueTitle.textContent = "Attribute " + (j + 1) + " Value";
aValueTitle.className = "title";
aValueInput.type = "text";
aValueInput.className = "input-box";
aValueInput.name = "a-value-" + (j + 1);
varBoxes.appendChild(aValueTitle);
varBoxes.appendChild(aValueInput);
varBoxes.appendChild(document.createElement("br"));
};
varBoxes.appendChild(document.createElement("br"));
varBoxes.appendChild(document.createElement("br"));
}
}
</script>
Just replace the below line in script then you should be able to access the value of each price element.
From:
var vPriceInput = form.vPrice;
To:
var vPriceInput = form[vPrice];

how can i make my calculation using math.sqrt right?

I just want to get the square root of total2 .. but it won't appear in the selected box ..
here is the javascript codes.
i'll comment the html codes.
function myFunction() {
var q1 = document.getElementById("qinput1").value;
var q2 = document.getElementById("qinput2").value;
var q3 = document.getElementById("qinput3").value;
var total = parseInt(q1) + parseInt(q2) + parseInt(q3);
document.getElementById("ainput3").value=total;
var a1 = document.getElementById("ainput1").value;
var a2 = document.getElementById("ainput2").value;
//from the total we got, lets assign it a variable for further calculation
var a3 = document.getElementById("ainput3").value=total;
var total2 = parseInt(a1)*parseInt(a2)/ parseInt(a3);
document.getElementById("ansA").value = total2;
var total3 = math.sqrt(parseInt(total2));
document.getElementById("sqaureD").value = total3;
}
function myShapes() {
document.getElementById('squareA').style.display =
document.getElementById('shapes').value == 'Square' ? 'block' : 'none'
}
<form action="" id="fcalculation">
<fieldset>
<legend>Calculation of qu</legend>
<label><i>Ultimate bearing capacity</i> <b>(qu) = </b></label>
<input id="qinput1" type="text" placeholder="c'NcFcsFcdFci"/> +
<input id="qinput2" type="text" placeholder="qNqFqsFqdFqi"/> +
<input id="qinput3" type="text" placeholder="½βγNFγsFγdFγi"/>
</fieldset>
</form>
it seems that the calculation part at the very end is not working. sorry its my first time to code.
Classname is Math not math
Try replacing
var total3 = math.sqrt(parseInt(total2,10));
with
var total3 = Math.sqrt(parseInt(total2,10));
Also, looking at your markup, there are no fields with id ainput1, ainput2 and ainput3.

get a new value input .innerHTML

I'm having some problem understanding how to get a new value from my span id='savings'. As you can see I need to make my bank account works. if a deposit is all good, but when I want to withdraw some money it starts from my starting point of 0, instead of starting from what I deposited.
var inputAmount = document.getElementById('inputAmount');
var withdBtn = document.getElementById('withdBtn');
var savingSpan = document.querySelector('#savings');
var myBalance = Number(savingSpan.innerHTML);
var depBtn = document.getElementById('depBtn');
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var depositBalance = savAmount + myBalance;
savingSpan.innerHTML = depositBalance;
});
withdBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var withdrawBalance = (myBalance.innerHTML) - savAmount;
savingSpan.innerHTML = withdrawBalance;
});
<h1></h1>
<div class="savings" id="accounts">
<h2>Savings Account</h2>
<h3> Your current balance is </h3>
<span>$</span> <span id="savings"> 00.00 </span>
<p>
<input id="inputAmount" type="number" placeholder="Enter amount here">
</p>
<p>
<button id="withdBtn" type="button">Withdraw</button>
<button id="depBtn" type="button">Deposit</button>
</p>
</div>
There are two mistakes in your code:
You're calling myBalance.innerHTML, but it should just be myBalance as this variable is already holding the value.
You need to update you myBalance variable when the buttons are clicked. Currently the
Simple solution: Just replace depositBalance and withdrawBalance with myBalance.
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
myBalance = savAmount + myBalance;
savingSpan.innerHTML = myBalance;
});
withdBtn.addEventListener('click', function(){
var savAmount = Number(inputAmount.value);
myBalance = myBalance - savAmount;
savingSpan.innerHTML = myBalance;
});
See also https://jsfiddle.net/enpo/wdu87Lek/.
You need to switch myBalance with savingSpan in the withBtn function. myBalance is a number and therefore doesn't have the attribut innerHTML
withdBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var withdrawBalance = (savingSpan.innerHTML) - savAmount;
savingSpan.innerHTML = withdrawBalance;
});
EDIT:
For multiple deposits, you also need to replace myBalance with Number(savingSpan.innerHTML) in the depBtn function. myBalance only gets sets once at the beginning and therefore doesn't represent the current balance.
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var depositBalance = savAmount + Number(savingSpan.innerHTML);
savingSpan.innerHTML = depositBalance;
});

Why does my value keep returning as "NaN"?

Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.

Categories