How to access form values with variable names? - javascript

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];

Related

Add 2 functions

I'm trying to add my getExamGrades and getLabGrades together by calling my other function to get a total grade but nothing I've tried works. Everything I've done so far just eliminates both of the functions I call and leaves everything blank. The code below works perfectly fine, just need help with the last part and then I can figure out the other variables and functions.
<!DOCTYPE html>
<html>
<header>
<script>
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
}
function getTotalGrades()
{
//var Total = Number(getExamGrades()) + Number(getLabGrades();
document.getElementByID("totalGrade").innerHTML = Total;
}
</script>
</header>
<body>
Exam1: <input type = "text" name="Exam1" value ="100" id="Exam1">
Exam2: <input type = "text" name="Exam2" value ="100" id="Exam2">
Exam3: <input type = "text" name="Exam3" value ="100" id="Exam3">
<br><br>
<button onClick="getExamGrades()"> Calculate Exam Grade </button>
Total: <output id="examGrade"> </output>
<br><br>
Lab1: <input type = "text" name="Lab1" value ="100" id="Lab1">
Lab2: <input type = "text" name="Lab2" value ="100" id="Lab2">
Lab3: <input type = "text" name="Lab3" value ="100" id="Lab3">
<br><br>
<button onClick="getLabGrades()"> Calculate Lab Grade </button>
Total: <output id="labGrade"> </output>
<br><br>
<button onClick="getTotalGrades()"> Calculate Total Grade </button>
Final Grade: <output id="totalGrade"> </output>
</body>
</html>
Your functions are not returning the values. If they did, then what you were trying would work. Try it like this:
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
return Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
return Labs;
}
function getTotalGrades()
{
var Total = Number(getExamGrades()) + Number(getLabGrades());
document.getElementById("totalGrade").innerHTML = Total;
}
There were a couple of other minor issues that I fixed for you too.
You can see a working example here: http://jsfiddle.net/8js5uewc/2/

How to create a remove/delete function button in javascript? Button that can delete an element

I have A Form in HTML. Here's my Code:
<div id="format">
<form id="myForm" onsubmit="myForm(event)">
<b>Name:</b></br>
<input type="text" name="name" id="name" required="required" ></input></br>
<b>Phone Number:</b></br>
<input type="phone" name="phone" id="phone" required="required" ></input></br>
<b>Birthday:</b></br>
<input type="date" name="bday" id="bday" required="required" ></input></br>
<b>Email:</b></br>
<input type="email" name="email" id="email" required="required" ></input></br>
<b>Password:</b></br>
<input type="password" name="pWord" id="pWord" required" ></input></br>
<button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>
</form>
<div id="sample"></div>
</div>
Here's my Javascript code. In this code, when I trigger the submitted button from html, it will display the info of the user and append a div for each submitted info of the users.
var data = [];
var i, item;
function myForm(event){
event.preventDefault();
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var bday = document.getElementById("bday").value;
var email = document.getElementById("email").value;
var pWord = document.getElementById("pWord").value;
var age = document.getElementById("bday").value;
var ageValue;
var Bdate = document.getElementById("bday").value;
var Bday = +new Date(Bdate);
ageValue = ~~ ((Date.now() - Bday) / (31557600000));
var theBday = document.getElementById("age");
theBday.innerHTML = ageValue;
var userObject = {
name: name,
phone: phone,
bday: bday,
email: email,
pWord: pWord,
ageValue: ageValue,
};
data.push(userObject);
document.getElementById("sample").innerHTML = ""; //Prevents duplicate
for (var i=0 ; i <data.length ; i++){
var theDiv ;
var container ;
var button;
theDiv = document.createElement( "div" );
button = document.createElement( "button");
button.setAttribute("id", "remove");
button.remove(sample);
theDiv.style = "background-color:pink; border-style:solid; margin:1%;";
for (item in data[i]) {
var x = item + ":" + data[i][item] + "</br>" ;
theDiv.innerHTML += item + ":" + data[i][item] + "</br>" ;
}
button.innerHTML += "Remove";
button.style = "background-color:maroon; color:white;";
container = document.getElementById( "sample" );
container.appendChild( theDiv );
theDiv.appendChild (button);
}
console.log(data);
}
I want to to create a button for each appended div. The button will have the function of removing the entire div where the button belong.
A reasonably simple algorithm to correctly remove objects from the list is to provide a data- attribute value on each remove botton that gives its original index in the data array. (The attribute name used below is data-index).
Then take the inline code that adds objects and turn it into three functions to
(re-)draw all objects held in the data array.
add a single object to data and redraw all objects.
remove an object from the data array (coded as a remove button onclick handler) and redraw all objects.
The code already redraws all object when adding a new object is added, so redrawing everything when removing an object keeps it on the same level of simplicity.
Example code for simplified form:
"use strict";
var data = [];
function myFormData(event){
// halper functions
function addData( userObject) {
data.push(userObject);
redrawList();
}
function removeData( event) {
var index = this.getAttribute("data-index");
data.splice( index,1);
redrawList();
}
function redrawList() {
var container = document.getElementById( "sample" );
container.innerHTML = ""; // reset list displayed on page
for (var index=0 ; index <data.length ; index++){
var theDiv = document.createElement( "div" );
var divHTML = "";
var button = document.createElement( "button");
var userObject = data[index];
for( var item in userObject) {
if( !userObject.hasOwnProperty( item)) {
continue; // ignore inherited properties
}
divHTML += item + ":" + userObject[item] + "</br>" ;
}
theDiv.innerHTML = divHTML;
theDiv.style = "background-color:pink; border-style:solid; margin:1%;";
button.type="button";
button.setAttribute("data-index", index);
button.innerHTML = "remove";
button.style = "background-color:maroon; color:white;";
button.onclick=removeData;
theDiv.appendChild (button);
container.appendChild( theDiv );
}
}
// handle form submit event to add an event
event.preventDefault();
// cut down form:
var name = document.getElementById("name").value;
var userObject = {
name: name
};
addData( userObject);
// console.log(data); // not used in code example
}
<div id="format">
<form id="myForm" onsubmit="myFormData(event);">
<b>Name:</b></br>
<input type="text" name="name" id="name" required="required" ></input></br>
<button type="submit" name="submit" id="submit" value="Submit"
onsubmit="myFormData(event)" >Submit</button>
</form>
<div id="sample">
</div>
</div>
Note the code uses getAttribute("data-index") in case target browser support for element.dataset is unknown or absent. Function names myForm and myData were changed to myFormData as I presume they are the same function.
Probable issue: the existing code comment that clearing the sample list prevents duplicates is wrong. In the example code, clicking the submit button multiple times adds the same user. You could add a test to check for duplicate email addresses when adding a user to the list, but such code is outside the scope of this question. You may also wish to consider resetting the form after adding data to the "sample" list.
check the fiddler, i have implemented with a single value 'name'.
var data = [];
var i, item;
function myForm(event){
event.preventDefault();
var name = document.getElementById("name").value;
var userObject = {
name: name
};
data.push(userObject);
document.getElementById("sample").innerHTML = ""; //Prevents duplicate
for (var i=0 ; i <data.length ; i++){
var theDiv ;
var container ;
var button;
var index;
theDiv = document.createElement( "div" );
button = document.createElement( "button");
index = document.createElement("input");
index.setAttribute('hidden', 'true');
button.setAttribute("id", "remove");
button.setAttribute("onclick", "removeItem(this)");
for (item in data[i]) {
var x = item + ":" + data[i][item] + "</br>" ;
theDiv.innerHTML += item + ":" + data[i][item] + "</br>" ;
index.value += i;
}
button.innerHTML += "Remove";
container = document.getElementById( "sample" );
container.appendChild( theDiv );
theDiv.appendChild (button);
theDiv.appendChild(index);
}
}
function removeItem(event){
let el = event;
let index = el.parentNode.lastElementChild.value;
el.parentElement.remove();
data.splice(index,1);
}
<div id="format">
<form id="myForm" onsubmit="myForm(event)">
<b>Name:</b>
<input type="text" name="name" id="name" required="required" >
<button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>
</form>
<div id="sample"></div>
</div>

Custom id's in javascript created elements

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.

I'm trying to add textboxes within ordered list onclick of a button using JavaScript and also increment ID name while adding the textbox

I tried using document.createElement, which works fine to add textbox but I can't increment ID name.
I am using it in a metro app.
function textBox(noOfInputTag){
noOfInputTag = noOfInputTag*1; // Convert to Number
//noOfInputTag is used to get total textbox you want to create
for(var i = 0; i <= noOfInputTag; i++){
var textbox = document.createElement('input');
textbox.type = 'text';`enter code here`
textbox.id = 'textBox_' + i; // As number of textbox increases id get incremented
document.body.appendChild(textbox);
}
}
textBox(2);
<form>
No. of lines:
<input type="text" id="number" value="0"/>
<br/>
<input type="button" id="button" value="Add Line" />
</form>
<div>
<ol id="linedata">
</ol>
</div>
document.getElementById('button').addEventListener("click", incrementValue);
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
var list = document.createElement('li');
var box = document.createElement('input');
box.type = 'text';
box.id = 'line' + value;
box.placeholder='Line ' + value;
list.appendChild(box);
document.getElementById("linedata").appendChild(list);
}

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.

Categories