Reputation: 1654
I am trying to pass the value of all the textareas on a page to a JSON table. For some reason I get a "cannot set value of undefined error", I dont understand since my Json is defined earlier.
Here is the code with the 2 functions.
function parseToJson() {
var json = {};
$("input.invoice_details").each(function () {
json[this.id] = $(this).val();
});
$("select.invoice_details").each(function () {
json[this.id] = $(this).val();
});
json.categories = {};
$("textarea.invoice_categories").each(function () {
if (this.value.trim() !== '') {
json.categories[this.id].values = splitInput(this);
json.categories[this.id].label = this.name;
}
});
console.log(JSON.stringify(json));
generatePreveiw(json);
}
function splitInput(textArea) {
var input = textArea.value.trim();
var lines = input.split("\n");
var array = [];
$.each(lines, function (indexLine, line) {
var columns = line.split("\t");
var obj = {};
$.each(columns, function (indexColumn, column) {
var columnName = columnsName.columnsName[indexColumn].name;
obj[columnName] = column;
});
array.push(obj);
});
return array;
}
Upvotes: 0
Views: 10312
Reputation: 780984
json.categories[this.id].values = splitInput(this);
json.categories[this.id].label = this.name;
should be:
json.categories[this.id] = {
values: splitInput(this),
label: this.name
};
You can't set the properties of an object when you haven't created the object first. You can use this object literal syntax to create the object and its properties in one step.
Upvotes: 4
Reputation: 6872
The problem is that you are trying to access a property of the object stored in json.categories[this.id]. Unfortunately it is undefined. Try the following:
function() {
if (this.value.trim() !== '')
{
//Initialize to an empty object if necessary
json.categories[this.id] = json.categories[this.id] || {};
json.categories[this.id].values = splitInput(this);
json.categories[this.id].label = this.name;
}
});
Upvotes: 0
Reputation: 943571
json.categories = {};
You have an empty object
json.categories[this.id].values = splitInput(this);
Now you are trying to access a property called this.id
from that object.
Since the object doesn't have any properties yet, that will always be undefined
You then try to assign undefined.value = splitInput(this)
, which throws an error.
You need to make sure json.categories[this.id]
has a value before you can set properties on it.
Upvotes: 0