javascript array displaying undefined in text area - javascript

So I am working on some home work right now and am having trouble understanding why my array is showing as undefined. Sorry if this is simple, but I am pretty new at this. I will try to explain what I am doing here.
I have three input fields where I gather a students last name, first name and grade. I get all those elements by their id's and put all those inputs into an array called studentGrade. I then push the contents of that array into another array called grades to then pass that as a parameter to a function called get_item_list. from there I try to loop through the contents of that parameter so that I can display it to the text field with the id of "scores".
I really appreciate all the input and hope I can learn what I am doing wrong.
var grades = [];
var $ = function (id) { return document.getElementById(id); }
var update_display = function () {
$("scores").value = get_item_list(grades);
$("last_name").value = "";
$("first_name").value = "";
$("score").value = "";
$("last_name").focus();
}
var student_grade_add_click = function() {
var studentGrade = [];
studentGrade["last_name"] = $("last_name").value;
studentGrade["first_name"] = $("first_name").value;
studentGrade["score"] = parseFloat($("score").value);
if ( studentGrade["last_name"] == "" ) return;
if ( studentGrade["last_name"] == "" ) return;
if ( isNaN(studentGrade["score"]) ) return;
grades.push(studentGrade);
update_display();
}
var get_item_list = function(item_list) {
if ( item_list.length == 0 ) {
return "";
}
var list;
for ( var i in item_list ) {
list += item_list[i] + "\n";
}
return list;
}
window.onload = function () {
$("add_button").onclick = student_grade_add_click;
$("last_name").focus();
}
this is the javascript I am working with
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Student Scores</title>
<link rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript" src="student_scores.js"></script>
</head>
<body>
<div id="content">
<h1>Student Scores</h1>
<div class="formLayout">
<label>Last Name:</label>
<input type="text" id="last_name" /><br />
<label>First Name:</label>
<input type="text" id="first_name" /><br />
<label>Score:</label>
<input type="text" id="score" /><br />
<label> </label>
<input type="button" id="add_button" value="Add Student Score" /><br />
</div>
<h2>Student Scores</h2>
<p><textarea id="scores" rows="5" cols="60"></textarea></p>
<div class="formLayout">
<label>Average score:</label>
<input type="text" id="average_score"/><br />
<label> </label>
<input type="button" id="clear_button" value="Clear Student Scores" /><br />
<label> </label>
<input type="button" id="sort_button" value="Sort By Last Name" /><br />
</div>
</body>
</html>
and there is the html I have made, thanks again.

I think you need to initialize list as a string prior to concatenating values to it:
var get_item_list = function(item_list) {
if ( item_list.length == 0 ) {
return "";
}
var list = "";
for ( var i = 0; i < item_list.length; i++) {
var current = item_list[i];
for ( var attr in current ) {
list += current[attr] + "\n";
}
}
return list;
}
Also, studentGrade is not array, it is an object (even though you are setting keys like an array):
var studentGrade = {};
My changes work, here is your updated fiddle: http://jsfiddle.net/LFhNQ/1/

Related

Google Apps Scripts - My button will not call the javascript function

This is the html code user input form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="marginauto" align="middle">
<style>
.marginauto {
margin: 10px auto 20px;
display: block;
}
</style>
<h1>
<img class="marginauto" align="middle" src="https://drive.google.com/uc?export=view&id=********" alt="*****">
Fabrication Time Record
</h1 >
<h2 class="marginauto" align="middle">
Information
</h2>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br>
<label for="jnum">Job number:</label><br>
<input type="text" id="jnum" name="jnum"><br>
<h2>
Operation
</h2>
<input type="radio" id="cut" name="operation" value="cut">
<label for="cut">Cut</label><br>
<input type="radio" id="drill" name="operation" value="drill">
<label for="drill">Drill</label><br>
<input type="radio" id="fitup" name="operation" value="fitUp">
<label for="fitup">Fit Up</label><br>
<input type="radio" id="weld" name="operation" value="weld">
<label for="weld">Weld</label><br>
<h2>
Comments
</h2>
<input type="text" id="comment"><br>
<br>
<button id="clockin">Clock in</button>
</div>
<script type="text/javascript">
document.getElementById("clockin").addEventListener("click",addLine);
function addLine(){
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var operation = document.getElementByName("operation");
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
}
google.script.run.addEntry(entry);
firstName.value = "";
lastName.value = "";
}
</script>
</body>
</html>
This is the script that takes user inputs from the html and (ideally) transfers them to a google spreadsheet:
function doGet(e){
Logger.log(e);
var html = HtmlService.createHtmlOutputFromFile("userForm");
html.setTitle("Record Time")
return(html)
}
function addEntry(entry){
Logger.log("Someone clicked the button");
var ssid = "1E81*****************QBmW1o4Q";
var ss = SpreadsheetApp.openById(ssid);
SpreadsheetApp.setActiveSpreadsheet(ss);
var database = ss.getSheetByName("Database");
SpreadsheetApp.setActiveSheet(database);
database.appendRow = ([entry]);
}
When I click the button, nothing happens. I am sure that I am calling the correct spreadsheet because I can read and write from the doGet() function, but there seems to be a problem with the addLine() function that I cannot find.
Any help is greatly appreciated, I am very new to web app development.
What I want is for the button to transfer the data from some text input fields to a google spreadsheet. I used multiple different button syntaxes but cannot nothing happens.
You are passing an object to addEntry you should pass an array.
Change
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
};
To
var entry = [
firstName.value,
lastName.value,
operation.value
];
Also you have a typo in your client script. Change
var operation = document.getElementByName("operation");
To
var operation = document.getElementsByName("operation");
However getElementsByName returns a node list so to find the checked radio button you need to add this to your client script.
let operations = document.getElementsByName("operation");
let operation = null;
for( let i=0; i<operations.length; i++ ) {
if( operations[i].checked ) {
operation = operations[i];
break;
}
}

Storing "Records" from an input field into in an array with Object Constructor and Javascript?

I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name" /></label></p>
<p><label>Age: <input class="text" type="text" id="age" /></label></p>
<p><label>Position: <input class="text" type="text" id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details" maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick="" value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
and here's my Javascript:
var employees = [];
//--------------------------------------------------------------------------------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//-----------------------------------------------------------------------------------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//--------------------------------------------------------------------------------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------------------------------------------
function sortAge(){
}
//--------------------------------------------------------------------------------------------------------------
function addRecord(){
}
//--------------------------------------------------------------------------------------------------------------
function writeRecords(){
//--------------------------------------------------------------------------------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------------------------------------------
function arrayButtons(){
}
I understand there's probably a lot of simple mistakes and stuff missing but i'm really having trouble grasping this,
Kind regards

Passing array input values to code.gs on google app scripting

I have a form with input array and I want to initialized the input value by another Global array value and pass the value to code.gs .
But I couldn’t get the value I passed in code.gs.
Would you help me please?
Thank you!
Html part
<form id="downloadpdf">
<input id="urlclass" type="text" name="urlname[]" />
<input type="submit" value="Download" />
</form>
Javascript
<script>
var urllink=[]; // Global variable a return from another function
$(document).ready(function() {
function another(){
var url=[]; // it is a dynamic value I get it from another function eg. url[0]=”www.abc.com” ,url[1]=”www.abcd.com”, url[2]=”www.abcde.com”....
urllink.push(url); // Assigning the global array value by the urls
}
$("#downloadpdf").submit(function() {
$("#urlclass").val(urllink); // assigning the input value by the Global array value.
google.script.run.withSuccessHandler(function(retsearch){
}).downloadthefile(this);
});
});
</script>
Code.gs
function downloadthefile(urlpass){
Logger.log(urlpass.urlname); // I couldn’t get the urls here
}
This is a simple HTML file communicating with Google Apps Script contained in a Spreadsheet. I test it a lot as a dialog and I also run it as a web app. The HTML file and the Google Apps Script communicate with each other and I pass the contents of 4 textboxes back to the Google Script as an array.
The Code.gs file:
function doGet()
{
var html = HtmlService.createHtmlOutputFromFile('index');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
function getData(a)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "M/d/yyyy' 'HH:mm:ss");
a.splice(0,0,ts);
var ss=SpreadsheetApp.openById('SPREADSHEETID')
ss.getSheetByName('Form Responses 1').appendRow(a);
return true;
}
function getURL()
{
var ss=SpreadsheetApp.openById('SPREADSHEETID');
var sht=ss.getSheetByName('imgURLs');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var urlA=[];
for(var i=1;i<rngA.length;i++)
{
urlA.push(rngA[i][0]);
}
return urlA;
}
The index.html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="data">
<br />Text 1<input name="t1" type="text" size="15" id="txt1" placeholder="Text 1" />
<br />Text 2<input name="t2" type="text" size="15" id="txt2" placeholder="Text 2" />
<br />Text 3<input name="t3" type="text" size="15" id="txt3" placeholder="Text 3" />
<br />Text 4<input name="t4" type="text" size="15" id="txt4" placeholder="Text 4" />
<br /><input type="radio" name="Type" value="Member" checked />Member
<br /><input type="radio" name="Type" value="Guest" />Guest
<br /><input type="radio" name="Type" value="Intruder" />Intruder
<br /><input type="button" value="submit" id="btn1" />
<br /><img id="img1" src="" alt="img1" width="300" />
</div>
<div id="resp" style="display:none;">
<h1>Response</h1>
<p>Your data has been received.</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#btn1').click(validate);
$('#txt4').val('');
$('#txt3').val('');
$('#txt2').val('');
$('#txt1').val('')
google.script.run
.withSuccessHandler(setURL)
.getURL();
});
function setURL(url)
{
$('#img1').attr('src',url[0]);
}
function setResponse(a)
{
if(a)
{
$('#data').css('display','none');
$('#resp').css('display','block');
}
}
function validate()
{
var txt1 = document.getElementById('txt1').value || '';
var txt2 = document.getElementById('txt2').value || '';
var txt3 = document.getElementById('txt3').value || '';
var txt4 = document.getElementById('txt4').value || '';
var type = $('input[name="Type"]:checked').val();
var a = [txt1,txt2,txt3,txt4,type];//This gets passed as an array;
if(txt1 && txt2 && txt3 && txt4)
{
google.script.run
.withSuccessHandler(setResponse)
.getData(a);
return true;
}
else
{
alert('All fields must be completed.');
}
}
function loadTxt(from,to)
{
document.getElementById(to).value = document.getElementById(from).value;
}
function radioValue()
{
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++)
{
if(radios[i].checked)
{
return radios[i].value;
}
}
}
console.log('My Code');
</script>
</body>
</html>

fill in the blank and multiple choice quiz

I was wondering if someone could help me? In my code below what if answers in question 2 were allowed to be in any order? Like: hips,body,knees or knees,hips,body and so on. How should I modify my code? Anyone please????
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Quiz</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
var answer_list = [
['False'],
['body,hips,knees']
// Note: No comma after final entry
];
var response = [];
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
function setAnswer(question, answer) {
response[question] = answer;
}
function CheckAnswers() {
var correct = 0;
var resp, answ;
for (var i = 0; i < answer_list.length; i++) {
resp = response[i].toString();
resp = resp.toLowerCase();
answ = answer_list[i].toString();
answ = answ.toLowerCase();
//#################################################################################################
if (resp == answ) {
correct++;
if(i==0){
document.forms[0].a1c.style.backgroundImage="url('correct.gif')";
document.forms[0].a1c.value = "";
}
else{
document.forms[0].a1d.style.backgroundImage="url('correct.gif')";
document.forms[0].a1d.value = "";
}
}
else{
if(i==0){
document.forms[0].a1c.style.backgroundImage = "url('incorrect.gif')";
document.forms[0].a1c.value = " ANS: False. Position the head snugly against the top bar of the frame and then bring the foot board to the infant's feet.";
}
else{
document.forms[0].a1d.style.backgroundImage = "url('incorrect.gif')";
document.forms[0].a1d.value = " ANS: " + answ;
}
//###################################################################################################
}
}
document.writeln("You got " + correct + " of " + answer_list.length + " questions correct!");
}
</script>
</head>
<body>
<form action="" method="post">
<div>
<b>1. When measuring height/length of a child who cannot securely stand, place the infant such that his or her feet are flat against the foot board.</b><br />
<label><input type="radio" name="question0" value="True" />True</label>
<label><input type="radio" name="question0" value="False" />False</label>
<br />
<textarea rows="2" cols="85" name="a1c" style="background-repeat:no-repeat"></textarea>
<br />
<b>2. When taking a supine length measurement, straighten the infant's
<input type="text" name="question1_a" size="10" />,
<input type="text" name="question1_b" size="10" />, and
<input type="text" name="question1_c" size="10" />.</b>
<br />
<textarea rows="2" cols="85" name="a1d" style="background-repeat:no-repeat"></textarea>
<br />
<input type="button" name="check" value="Check Answers" onclick="setAnswer(0,getCheckedValue(document.forms[0].question0));setAnswer(1,[document.forms[0].question1_a.value,document.forms[0].question1_b.value,document.forms[0].question1_c.value]);CheckAnswers();" />
</div>
</form>
</body>
</html>
The easiest way IMO is to sort the user's answers and sort the correct answers in CheckAnswers().

how to sum radio button values only one time?

I am using this code to sum values from multiple radio buttons :
$(document).ready(function(){
var total = 50000;
$("input[type=radio]").change(function(){
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
});
the problem is that when user click on a radio button in a group and then select another radio button in that group the new value will be add to this, i want to only add one of the values to the total value.
for example in this group :
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
when first time a user select seconed radio the 5000 will be add to total price, but if he change it to third option, 15000+5000 will be add to total, i want to have only one of them !
The problem seems, to me, that the total var is declared out of the scope of the change callback. This will cause the closure of the change callback to contain the total variable, so it's value will be persisted across subsequent change calls.
If declare the total within this callback, you should be fine:
$("input[type=radio]").change(function(){
var total = 5000; // => declared locally, so initialized at each change.
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
I wrote a simple example demonstrating this recently (although I did it without using jQuery).
Just store the value you add, and then subtract it from the total before adding a new one.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Radio Test</title>
</head>
<body>
<form action="" method="get" id="myForm">
<fieldset id="myRadioGroup">
<legend>Radios</legend>
<div>
<label> <input type="radio" value="0" name="add" checked> 0 </label>
</div>
<div>
<label> <input type="radio" value="20" name="add"> 20 </label>
</div>
<div>
<label> <input type="radio" value="30" name="add"> 30 </label>
</div>
</fieldset>
<div id="total">45</div>
</form>
<script type="text/javascript">
(function () {
var group = document.forms.myForm.elements.add;
var currentValue = function currentValue () {
for (var i = 0, j = group.length; i < j; i++) {
if (group[i].checked) {
return Number(group[i].value);
}
}
};
var oldValue = currentValue();
var total = document.getElementById('total').firstChild;
var update = function update () {
var current = currentValue();
total.data = Number(total.data) - oldValue + current;
oldValue = current;
};
for (var i = 0, j = group.length; i < j; i++) {
group[i].onchange = update;
}
}());
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>
W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
</body>
<script type="text/javascript">
$(function()
{
$('input:radio').change(function()
{
var total = 50000;
$('input:radio:checked').each(function()
{
if (isNaN(this.value))
total = total;
else
total += parseFloat(this.value);
});
$('.price_amount').text(total);
});
});
</script>
</html>

Categories

Resources