inserting text-field to table cell using javascript - 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.

Related

How to convert HTMLCollection to string

I'am working on a bot that will edit some form on website, one part of the form is where is some html. I copy data from the converting to HTMLCollection do some actions, and then i want to save it back to the . And in case to do so i need to convert HTMLCollection object back to a string.
How i get and convert the data:
var htmlFromTextArea = document.getElementById('nameOfTextArea').value;
var htmlObject = document.createElement('div');
htmlObject.innerHTML = htmlFromTextArea;
var htmlElements = htmlObject.getElementsByTagName("*")
And now i need htmlElements to become string again
I tried the following but it seems not working:
var stringWithHtmlTobeSavedInTextArea = htmlElements.text;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.textContent;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.innerText;
Yes, htmlElements is HTMLCollection. So seperate each element and add outerHTML of element to string using loop.
var htmlObject = document.createElement('div');
htmlObject.innerHTML = "<a>anchor</a><p>paragraph</p>";
var htmlElements = htmlObject.getElementsByTagName("*");
var stringWithHtmlTobeSavedInTextArea="";
for (i = 0; i < htmlElements.length ; i++){
stringWithHtmlTobeSavedInTextArea += htmlElements[i].outerHTML;
}
console.log(stringWithHtmlTobeSavedInTextArea);
Please note that, above solution is not correctly working in case if the HTML inside div element is like <div><a>anchor</a></div>
So It is better to use innerHTML or get actual text from <textarea> eg.
var stringWithHtmlTobeSavedInTextArea = htmlObject.innerHTML;
//Or
var stringWithHtmlTobeSavedInTextArea = htmlFromTextArea;

Putting forum data into separate arrays

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.

How to assign variable to json object

'I'm trying to assign a variable from a parent div to the json string of a child table and can't seem to get my javascript straight.
What I'd like to see, or some variation of:
{"blocks":[{"id":"115",courses:[{"Semester":"S,F","Credits":"3","Subject":"ACT"}‌​, {"Semester":"F","Credits":"6","Subject":"CSI"}]}]
And the jQuery I have so far.
$('#update').click(function (e){
var table = $('#table').tableToJSON();
var blockId = $('#table').closest('div.Block').attr('id');
table = {"block":table};
document.getElementById('courseList').value = JSON.stringify(table);
}
I'm not sure how to add in the variable that I need in the object? How would I insert blockId?
I'm assuming bracket notation is what you're really looking for :
$('#update').on('click', function(){
var table = $('#table').tableToJSON();
var blockId = $('#table').closest('div.Block').attr('id');
var table2 = {};
table2[blockId] = table;
$('#courseList').val( JSON.stringify(table2) );
});

Jquery ID selector doesnt work with a variable

I've read a billion questions like this, but never found an answer yet.
Anyway, when I type
var variableContainingID = "header";
var div = $("#"+variableContainingID);
It returns 'undefined'
But when I type
var variableContainingID = "header";
var div = $('[id^="'+variableContainingID+'"]');
It works fine.
Any ideas why?
UPDATE
var json = '{"divs":['
var children = $(".parent_container > div");
var idArray = [];
var numArray = [];
for (var x=0; x<children.length; x++) {
var eleid = $(children[x]).attr("id");
idArray.push('"'+eleid+'"');
numArray.push(x+1);
}
var idString = idArray.join(",");
var numString = numArray.join(",");
json += idString;
json += '],"number":['+numString+']}';
var obj = JSON.parse(json);
for (x in obj["divs"]) {
var div = $('[id^="'+obj["divs"][x]+'"]');
}
Do you think the double quotes could be throwing it off?
As you wrote in your question:
var div = $("#"+variableContainingID);
var div = $('[id^="'+variableContainingID+'"]');
These two lines are not identical. The first one, will select an element with id of header. The second one,
selects elements that have the specified id with a value beginning exactly with a given string (header).
So if you have an element like this:
<div id="headerHere"></div>
The first one ($("#"+variableContainingID)) can't select it, but the second one ($('[id^="'+variableContainingID+'"]')) can select that element.
This is because you used ^= in your selector. See jQuery API: Attribute Starts With Selector (name^="value").
It's worth to see all attribute selectors in jQuery.
Attribute Selectors in jQuery

Dynamic Spreadsheet using HTML + JavaScript only

So I've got a couple of questions. I'm attempting to create a dynamic spreadsheet, with the capabilities of having values inserted into it as well as (and only needed) being able to process the SUM() formula. The problem I've run into right now, is when inserting a value.
Firstly allow em to show the JS I have for the insertion. The HTML table is using id values of 1_1,1_2 etc.
EDIT: Fixed the var column= document.getElementById(insert); line, however it doesn't seem to want to commit any inserted value. Shouldn't it simply be a return statement to commit a change to the html field?
function insertValue() {
var v = document.getElementById("submitText");
v = v.value;
var row = document.getElementById("row");
row = row.value;
var col = document.getElementById("col");
col = col.value;
var insert = row + "_" + col;
insert = insert.toString();
var col = document.getElementById("col");
EDIT:: return column.value = v;
} //end function
When I'm attempting to take the insert variable and use it as the id value, it breaks the whole program. Should I be casting the insert var to something other then a string?
I assume
var column.getElementById(insert);
should be
var column = document.getElementById(insert);
Your line of code is invalid.
function insertValue() {
var v = document.getElementById("submitText");
v = v.value;
var row = document.getElementById("row");
row = row.value;
var col = document.getElementById("col");
col = col.value;
var insert = row + "_" + col;
// Don't really think this is necessary, so probably remove it.
//insert = insert.toString();
var column = document.getElementById(insert); // Compare this line to yours
column.value = v;
} //end function
The reason of having error is because you're not writing it correctly.
var column.getElementById(insert); is wrong syntax. var is supposed to be followed by a variable name, and you can assign an initial value to it.
It is surprising that though you got it correct in the beginning but fail to do so later.
But the next time you have an error in your JavaScript code, check the browser's JavaScript Console. It can probably be opened using F12, and inside you will see the error is shown. Then you will not need to always come up and ask a question for every single problem you met. :)

Categories