Putting forum data into separate arrays - javascript

container.appendChild(document.createTextNode("Load Location " + (i) + " (m): "));
var input = document.createElement("input");
input.type = "text";
input.name = "loadLocation" + i;
input.id = "loadLocation" + i;
container.appendChild(input);
container.appendChild(document.createTextNode(" Load Magnitude " + (i) + " (N): "));
var input = document.createElement("input");
input.type = "text";
input.name = "loadMagnitude" + i;
input.id = "loadMagnitude" + i;
container.appendChild(input);
I'm dynamically generating two different types of forum elements, the location of loads and the magnitude of loads. After getting the input I want to use JavaScript to put each set of data into their respective arrays to end up with something like:
loadLocation [] = [loadLocation1, loadLocation2, ...]
loadMagnitude[] = [loadMagnitude1, loadMagnitude2, ...]
Is there any way to loop thorough form elements based on a partial match of id/name? If not is there a simpler way I could set this up?

You can use the children property to obtain any elements that are within the form. As for entering the data into the correct array, you can use objects for that.
I'm assuming the form elements have an id or name that represent what kind of data it is receiving, thus using objects you can assign the id as a property and an empty array as its value:
var loadDataArrays={
"location":[],
"magnitude":[]
};
function assignData(formID){
var form=document.getElementById(formID);
var formChildren=form.children;
//Loop through child elements of form element (inputs)
for(var i in formChildren){
var child=formChildren[i];
//Using the form id, you can push the data of its child elements to the correct array
loadDataArrays[formID].push(child.id);
}
}
To access the array you can simply do something like:
var locationData=loadDataArrays["location"];

Ok I think I might have figured it out. Add a class for each category and getElementsByClass. I believe that will return an array in the order that the elements were created.

Related

Submitting a form through google scripts

I need to submit a form in a google script but get this error:
TypeError: Cannot call method "withItemResponse" of undefined
According to the link below, this is how it should be set up https://developers.google.com/apps-script/reference/forms/form#createResponse()
Code:
//Submit form
var formID = row[24];
var form = FormApp.openById(formID);
Logger.log(form.getId()); //returns correct ID
form.createResponse() ;
form.FormResponse.withItemResponse('Core Teachers', logSummary);
//form has only two questions, a short text and a paragraph text
form.FormResponse.submit();
form.createResponse() returns a FormResponse, which you need to assign to a variable.
also, withItemResponse() expects an object of type ItemResponse. I am not familiar with google forms, but maybe this gets you in the right direction:
var formID = row[24];
var form = FormApp.openById(formID);
var formResponse = form.createResponse();
// get items of form and loop through
var items = form.getItems();
for (index = 0; index < a.length; ++index) {
var item = items[index]
// Cast the generic item to the text-item class. You will likely have to adjust this part. You can find the item classes in the documentation. https://developers.google.com/apps-script/reference/forms/item-type.
if (item.getType() == 'TEXT') {
var textItem = item.asTextItem();
var itemresponse = textItem.createResponse('Core Teachers');
formResponse.withItemResponse(itemresponse);
}
}
formResponse.submit();
Generally, when the documentation of a method lists as parameter type something else than primitive types like String or Boolean you need to create or aquire an object of that type, like I did with createResponse. You need to familiarize yourself with these and other principles because the GoogleAppsScript documentation assumes knowledge of them.

inserting text-field to table cell using javascript

I am making a program in which I want to add an input field to a table cell.
Look at the code below:
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
newf.appendChild(newl);
}
newf gets the value of td_song,td_artist etc and these are already defined as:
var td_song = document.createElement("td");
var td_artist = document.createElement("td");
var td_genre = document.createElement("td");
in the same function and then I've appended them to a table and it works fine
but when I am creating the input element then there's an error:
Uncaught TypeError: newf.appendChild is not a function
I know it has no end tag and it needs to be in a form element, but the error is same when I try to add any other element.
Help!
the value stored in newf is a string, not a DOM element; appendChild is not a valid method on strings. Just because the string value stored in newf matches the name of a variable you created (td_song, etc), does not mean it is now a handle to that element. You would be better of storing your created elements in an object, keyed off of that value:
var elems = {
td_song: document.createElement("td"),
td_artist: document.createElement("td"),
td_genre: document.createElement("td")
};
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
elems[newf].appendChild(newl);
}
After this line, the contents of newf is simply a string reading "td_song" for example.
var newf = "td_" + arr_title[title];
You are probably getting a JS error of "newf is not a function" ?
If you want newf to really be the one of those vars, you could explore using eval()
var newf = eval("td_" + arr_title[title]);
Does the <td> you're trying to append to have an ID of "td_" + arr_title[title]?
If so, you need to do...
var newf = document.getElementById("td_" + arr_title[title]);
newf.appendChild(newl);
newf is a string and you can't append child to string, if you want to refer to the variable with this name you should use window :
window[newf].appendChild(newl);
Hope this helps.

Pushing object to array results in same value

I have the following javascript code that does not work as I would expect it to. I have a list of checkboxes of which two of the items are "TestDuration" and "AssessmentScores". I'm trying to iterate through the list (which works fine) and have it add the values that are checked to the array.
var SAIndex = 0;
var SSIndex = 0;
var ScoresIndex = 0;
var SubAssessments = [];
var SubAssessmentScores = [];
//Get to the container element
var SSList = document.getElementById("islSubAssessmentScore_container");
//turn it into an array of the checkbox inputs
SSList = SSList.getElementsByTagName("input");
//create a temporary object to store my values
var tempPair = new Object();
//iterate through the checkbox lists
for(var i = 1; i < SSList.length;i++)
{
//if the value is checked add it to the array
if (SSList[i].checked)
{
var P = SubAssessments[SAIndex];
var V = SSList[i].value;
//tempPair.Parent = SubAssessments[SAIndex];
tempPair.Parent = P;
//tempPair.Value = SSList[i].value;
tempPair.Value = V;
//show me the values as they exist on the page
alert(tempPair.Parent + "|" + tempPair.Value);
SubAssessmentScores.push(tempPair);
//show me the values I just added to the array
alert(SubAssessmentScores.length-1 + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Parent + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Value);
//uncheck the values so when I refresh that section of the page the list is empty
SSList[i].checked = false;
}
}
//output the list of objects I just created
for (i = 0;i < SubAssessmentScores.length;i++)
alert(i + "|" + SubAssessmentScores[i].Parent + "|" + SubAssessmentScores[i].Value)
Now what happens is that when I iterate through the list I get the following alerts:
-first pass-
StudentID|TestDuration
0|StudentID|TestDuration
-second pass-
StudentID|AssessmentScores
1|StudentID|AssessmentScores
This is what I expect to output... However at the end of the code snippet when it runs the for loops to spit out all the values I get the following alerts...
0|StudentID|AssessmentScores
1|StudentID|AssessmentScores
I can't for the life of me figure out why it's replacing the first value with the second value. I thought it might be using a reference variable which is why I added in the P and V variables to try to get around that if that was the case, but the results are the same.
This is because you are adding the same variable every iteration of the loop.
Try changing your push like this:
SubAssessmentScores.push({
Parent: P,
Value: V
});
That said, I recommend you study a little more javascript and conventions in the language, for example your variable naming is frowned upon because you should only use capital letters on the beginning of a name for constructor functions.
A good book is Javascript the good parts by Douglas Crockford.

get name and id of all text box's in HTML body using java script

Is it possible to get name and id of all text boxes in HTML body using JavaScript. If it is possible please give me a example or method.
You need to learn about document.getElementsByTagName and a for loop
If you want to use jQuery, learn about the element selector, .each(), and .prop()
Untested version
var textboxes = document.getElementsByTagName("INPUT");
for (var i=0;i<textboxes.length;i++)
{
var textbox = textboxes[i];
if (textbox.type.toLowerCase() == "text")
{
alert("Hurray, I found a text box. Name and Id are: " + textbox.name + ", " textbox.id);
}
}
Or using jQuery
$("input[type='text']").each(function() {
alert("Hurray, I found a text box. Name and Id are : " + $(this).attr("name") + ", " + $(this).attr("id"));
});
So you would get all the necessary input fields. For this demo I'll keep at regular input fields. You can expand this example for radio buttons with the same name or select boxes.
It stores all the properties in an object literal {} and outputs the object to demonstrate.
var arr = document.getElementsByTagName("input"),
i = 0,
len = arr.length,
obj = {},
inp,
output = document.getElementById("output");
// store attributes name and id
for (;i<len;i++){
inp = arr[i];
obj[inp.id] = inp.name;
}
// output obj properties and values
for (var prop in obj){
if (obj.hasOwnProperty(prop)){
output.innerHTML += prop + ": " + obj[prop];
}
}
Also note that looping over array-like objects (storage of properties) and looping over object literals (output) is a bit different.
Is this something you had in mind?
DEMO: http://jsfiddle.net/tive/4JrUf/
Using this:
$('#yourid').attr('name')
$('#yourid').attr('id')

How to relate or associate an object in JavaScript to an HTML element?

How to relate or associate an object in JavaScript to an HTML element?
For each object in an array, I generate a checkbox input element based on that object.
If I add an event listener to capture the checkbox changes, how do I retrieve the object associated with that element?
As other answers point out, generating a unique id for each DOM node allows you to use those as keys in an Object.
Another possibility is that many frameworks provide utilities for assigning data to DOM elements. For example, in jQuery you can do it by writing $(checkbox).data('mydata', obj) or in YUI Y.one(checkbox).setData('mydata', obj).
You can generate an ID for each of the checkboxes, and store the ID in the corresponding object. Then, in the event handler, you can get the ID of the changed checkbox and find the appropriate object based on that by iterating over the array.
To make it even easier to find the object, you can also map the IDs to objects (e.g. objectsByID[someID] = someObject). With this approach, you don't even have to iterate over the array.
Example of how to create the objectsByID map:
var objectsByID = {};
for (var i = 0; i < objects.length; i++) {
var id = "checkbox_" + i;
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("id", id);
// ...
objectsByID[id] = objects[i];
}
You give a progressive ID to each checkbox, starting from "checkbox0", and when you click on a checkbox you check the relative ID number, which correspond to the object in array[x].
Here is a really simple example.
Create a global object, store additional objects when you're creating the checkboxes, identified by a unique name. Set the name or id attribute of the checkbox element to this unique name.
var source = [];
var data = []; //Your data
var appendTo = document.body;//Anywhere
for(var i=0; i<data.length;i++){
var identifier = "chk"+i;
var inp = document.createElement("input");
inp.type = "checkbox";
inp.name = identifier;//.name or .id - it's up to your preference
inp.addEventListener("change", function(ev){
if(this.checked){
callback(source[this.name]);//calls function callback, passing the original object as an argument.
}
}, true);
appendTo.appendChild(inp);
source[identifier] = ...//your object.
}

Categories