I've this HTML table:
<table class="table table-condensed">
<thead>
<tr>
<th><input type="checkbox" id="toggleCheckboxSelFabricante" name="toggleCheckboxSelFabricante"></th>
<th>Fabricante</th>
</tr>
</thead>
<tbody id="selFabricanteBody">
<tr>
<td><input type="checkbox" name="selChkFabricante" id="selChkFabricante3" value="3"></td>
<td>Eos est ipsam.</td>
</tr>
</tbody>
</table>
I need to create a key => value for manufacturerColl var where id is the value of each checked checkbox (first td on the table) and name is the text on the second column but don't know how to. This is what I've in my code:
var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
modelBranchManufacturerCollection;
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push(checkedManufacturers[j].value);
}
for (var i = 0; i < checkedModelBranch.length; i++) {
modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
if (modelBranchManufacturerCollection) {
for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).html(modelBranchManufacturerCollection.manufacturerKeyCollection[k] + '<br/>');
}
}
}
What I need in others words is for each manufacturerColl have and id => name, ex:
manufacturerColl[] = {
id: someId,
name: someName
};
And I'm not sure but maybe this could work:
// move foreach selected checkbox and get the needed
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push({
id: checkedManufacturers[j].value,
name: "" // how do I get the value on the second column?
});
}
Which is the right way to do this? How do I get the value on the second column on each iteration?
Approach
I don't know if this is complete right but is what I've done and it's buggy. See the code:
var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
// I added this var to get all the names
checkedManufacturersName = $("#selFabricanteBody").find("input[type='checkbox']:checked").parent().next('td').text(),
manufacturerColl = [],
modelBranchManufacturerCollection;
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push({
id: checkedManufacturers[j].value,
// Here I'm tying to put the entire name but get only the first character
name: checkedManufacturersName[j]
});
}
for (var i = 0; i < checkedModelBranch.length; i++) {
modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
if (modelBranchManufacturerCollection) {
//$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);
for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
// then I render the name attribute from the collection
$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
}
}
}
Why I'm inserting/getting the first character only and not the complete string?
//Since your input and text are wrapped in td elements
In the code:
var checked = $('#selFabricanteBody').find('input[type="checkbox"]:checked');
var arr = [], j = checked.length, item;
while(j--) {
item = list[j];
//gets the text from the next child, assumes its the text
//if the text is before checkbox, use previousSibling
arr.push({id: item.value, name: item.parentNode.nextSibling.nodeValue});
}
This is what I use to create an object, for sending to a controller method that is looking for a class/model as a parameter:
function ExtractModel(array) {
var modelString = '';
var model = {};
//var array = arrayString.split('&');
var isObjectModel = $.isPlainObject(array);
if (!isObjectModel) {
$(array).each(function (index, element) {
var typeId = element.split('=')[0];
var val = element.split('=')[1];
if (element == null) { } else {
model[typeId] = (val);
}
});
} else {
model = array;
}
return model;
};
So, with this, I am taking a url parameter string and creating an object from it; the parameter string is generated from serializing the form. The "model" automatically creates the property that is represented by "typeId"; if "typeId" = "hello", then a new property or object item will be created, named "hello" (model.hello will get you a value). You can use this same logic to loop through the elements on your page to populate the object with multiples. Make sure to set your variable "modelBranchManufacturerCollection" equal to {}, and to then set the index of where to insert a new one.
This should do what you want:
var ids = [1, 2, 3, 4, 5, 6]
var names = ['a', 'b', 'c', 'd', 'e', 'f']
var mainObj = {};
$(ids).each(function (index, element) {
var miniObj = {};
miniObj['id'] = ids[index];
miniObj['name'] = names[index];
mainObj[index] = miniObj;
});
returns 6 items of id and name.
Related
I'm having issues to get the stored data in my array. I can't see where is the problem on my function and why is returning undefined elements.
This is the function where I store data in the array:
function getTaskKidData(str) {
var tasks = $('#tasks_data > div');;
var formated_tasks = [];
var formated_kids = [];
formated_homeworks = [];
tasks.each(function(index) {
var task_kids = $(this).find('ul').eq(0).find('li');
var task_homeworks = $(this).find('ul').eq(1).find('li');
if (task_kids.length > 0 && task_homeworks.length > 0) {
task_kids.each(function(index) {
var kid_name = $(this).text().trim();
if (str == "kid"){
var kid = $('#kid_list > li > a[class*="active"]').text().replace(window.location.pathname.split('/')[2],'').trim();
if (kid == kid_name){
formated_kids.push({'name': kid_name});
}
}else{
formated_kids.push({'name': kid_name});
}
});
task_homeworks.each(function(index) {
var homework_name = $(this).find('p').eq(0).text().trim();
var homework_date = $(this).find('p').eq(1).text().trim();
formated_homeworks.push({
'name': homework_name,
'date': homework_date,
});
});
formated_tasks.push({
'kids': task_kids,
'homeworks': task_homeworks,
})
}
});
return formated_tasks;
}
I don't understand why the objects in the output of the array are "li" tags if I'm storing data as text. The output of the array is the next one:
This is the code where I'm trying to get the data:
var tasks = getTaskKidData("kid");
console.log(tasks)
for (let i = 0; i < tasks.length; i++) {
console.log("schedule");
for (let j = 0; j < tasks[i]['kids'].length; j++) {
console.log(tasks[i]['kids'][j]['name']);
}
for (let j = 0; j < tasks[i]['homeworks'].length; j++) {
console.log(tasks[i]['homeworks'][j]['name']);
console.log(tasks[i]['homeworks'][j]['date']);
}
}
And this is the output when I run the code:
Any idea of the problem?
Thanks for reading!!
In your code you have
var task_kids = $(this).find('ul').eq(0).find('li');
and later you log task_kids. The log output shows li elements because that was what you selected.
I'm building a table with HTML and then have created a function which allows me to select a cell. I also have a text field, with a function which will both change the innerText of the cell to the value in the text field and push that value into an array of the data in each table cell. I am then saving it to localStorage.
Here I encounter my error: how can I properly retrieve the data from the localStorage variable and repopulate the table with the values in the array?
Here's my code
omitting the table creation, textEntering, functions because they appear to be working fine
function save() {
localStorage.setItem("tblArrayJson", JSON.stringify(tblArray));
document.getElementById("lblInfo").innerHTML = "Spreadsheet saved.";
}
This is working because in a test function I can print the tblArrayJson in an alert. Next I am trying to load the data back to the table:
function loadSheet() {
var loadedData = JSON.parse(localStorage.getItem("tblArrayJson"));
var loadedTable = document.getElementById("SpreadsheetTable");
var currRow, cell;
alert("the retrieved JSON string contains: " + loadedData);
for (var i = 0; currRow = loadedTable.rows[i]; i++) {
for (var j = 0; cell = currRow.cells[j]; j++) {
cell.innerHTML = loadedData.shift();
}
}
}
The alert displaying the loadedData is working correctly. So what is it about my loop that is failing to insert the array values back into the table? They just stay blank.
Is there a problem with the way I'm using the function? Here is my button with the onclick:
<input id="btnLoad" type="button" onclick="loadSheet();" value="Load" />
localStorage is an object.
A loop through an object for(var key in object) {} is different to a loop through an array for(var i = 0; i < arr.length; i += 1) {}.
If the data looks like
var loadedData = {
0: ["cell1", "cell2", "cell3"],
1: ["cell1", "cell2", "cell3"]
}
the loops should look like
for(var key in loadedData) {
var row = loadedTable.insertRow();
for(var i = 0; i < loadedData[key].length; i += 1) {
var cell = row.insertCell(i);
cell.innerHTML = loadedData[key][i];
}
}
Example
var loadedData = {
0: ["cell1", "cell2", "cell3"],
1: ["cell1", "cell2", "cell3"]
}
function loadSheet() {
//var loadedData = JSON.parse(localStorage.getItem("tblArrayJson"));
var loadedTable = document.getElementById("SpreadsheetTable");
for (var key in loadedData) {
var row = loadedTable.insertRow();
for (var i = 0; i < loadedData[key].length; i += 1) {
var cell = row.insertCell(i);
cell.innerHTML = loadedData[key][i];
}
}
}
loadSheet();
<table id="SpreadsheetTable"></table>
Your for loop is missing the terminating condition. I added that to mine, you're free to modify to fit your needs.
var data = {
0: ["cell1", "cell2", "cell3"],
1: ["cell4", "cell5", "cell6"]
};
// localStorage.tblArrayJson = JSON.stringify(loadedData);
function loadSheet() {
// var data = JSON.parse(localStorage.tblArrayJson);
var table = document.getElementById("SpreadsheetTable");
var row, cell;
// Used Object.keys() to get an array of all keys in localStorage
for (var key of Object.keys(data)) {
row = table.insertRow();
for (var i = 0; i < data[key].length; i++) {
cell = row.insertCell(i);
cell.innerHTML = data[key][i];
}
}
}
loadSheet();
<table id="SpreadsheetTable"></table>
I have loop going though form values, it is working fine throwing out the values based on the input name. But I would also like to be able to target by specific element id.
This is an example form:
_inputFields: function() {
var rows = [];
for(var i = 1; i <= 12; i++) {
var placeHolder = 'Intro text line ' + i;
var inputID = 'inputIntroText ' + i;
rows.push(<input type="text" className="form-control input-size-lg" name="formInput" id="inputText" placeholder={placeHolder}/>);
rows.push(<input type="text" className="form-control input-size-lg" name="formInput" id="inputTime" placeholder={placeHolder}/>);
}
So I can loop through and grab everything by name i.e. 'formInput' but how can I then grab formInput[inputText] and formInput[inputTime]?
This is my current loop through the values :
// gather form input
var elem = document.getElementsByName('formInput');
console.log(elem);
// Build the object
var obj = {
"DataObject": {
"user": {
"-name": "username"
},
"contentFile": {
"-filename": "Breaking_News",
"lock": {
"-fileIsBeingEdited": "false"
},
"content": {
"line": []
}
}
}
};
var line = obj.DataObject.contentFile.content.line;
for (var i = 0; i < elem.length; i++) {
if (elem[i].value != '') {
line.push({
"-index": i,
"-text": elem[i]['inputText'].value,
"-time": elem[i]['inputTime'].value
});
}
};
If I try:
"-text": elem[i]['inputText'].value,
"-time": elem[i]['inputTime'].value
I get the error: Cannot read property 'value' of undefined
This errors because elem[i]['inputText'] is undefined. This is because you are trying to lookup the inputText property of the element, which doesn't exist.
elem is an array, so I'd recommend using something like filter.
"-text": elem.filter(function(item) {
return item.id === 'inputText';
})[0].value;
Also, you should remove the for loop or you will get a duplicate line.
function getElementById(elems, id){
return elems.filter(function(item) {
return item.id === id;
})[0];
}
var line = obj.DataObject.contentFile.content.line;
line.push({
"-text": getElementById(elem, 'inputText').value,
"-time": getElementById(elem, 'inputTime').value
});
Here's an example jsfiddle.
You can use elem[i].id:
var line = obj.DataObject.contentFile.content.line;
for (var i = 0; i < elem.length; i++) {
if (elem[i].value != '') {
line.push({
"-index": i,
"-text": elem[i].id
// Since you are looping through the inputs, you will get the `inputTime` in the 2nd iteration.
});
}
};
I create a form with matrix like this:
for(var i = 0; i < rows; i++)
{
for(var j = 0; j < columns; j++)
{
var input = $('<input>')
.attr({
class: 'matrix_cell',
value: 0});
form.appendChild(input[0]);
}
var br = $('<br>')[0];
form.appendChild(br);
}
And I want to read a matrix that user inputted to two-dimensional array and then pass it to php file in ajax query.
I tried this way:
function getMatrix(){
var matrix_row = []
$("#matrix_form").find("input").each(function(i){
var value = $(this).val();
if (!isNaN(value)){
matrix_row[i] = value;
}
});
return matrix_row;
}
But it reads matrix to onedimensional array.
See http://jsfiddle.net/hcbLozd7/
function getMatrix(){
var matrix_row = [];
var ind = 0;
$("#frm").contents().each(function(i,e){ //for all contents in div
if (this.nodeName == "INPUT") //if it's input
{
if (!matrix_row[ind]){ //it matrix doesn't have a new array, push a new array
matrix_row.push([]);
}
matrix_row[ind].push($(this).val()); //add input value to array inside array
}
else{ //when element is br
ind++; //increment counter
}
});
return matrix_row;
}
I am developing a simple add-on with Firefox SDK that allows the user to review the stored data.
I would like to show the items in a panel with a table. The table is created dynamically with the data incoming from the data-base. Firstly, In the JavaScript code I create the items with their properties, then I create a table with the properties as row and I append the items with the value of each properties.
I have some problems: the table has only the item's name as first row and the properties name as first column without the value in the cells. It seems that the code is not executed in order, but it seems that the faster functions are executed first.
This is the code:
self.on('message', function() {
var container = $('#container');
container.empty();
items = [];
self.port.emit('getItem');
});
self.port.on('items', function(response) {
var ok = 0;
var items = [];
var table = $('#tableContainer #table').clone();
var container = $('#container');
table.append("<tr id=first><th> </th></tr>");
var json = eval('('+ response + ')');
for (var i = 0, len = json.length; i < len; ++i) {
var item = {
id: json[i],
properties: []
};
items.push(item);
}
items.forEach ( function(item) {
table.find('#first').append("<th id="+item.id+">"+item.id+"</th>");
self.port.emit('detailsItem', item.id);
self.port.on('details'+item.id, function(response) {
var details = eval('('+ response + ')');
var description = [];
ndet = details.length;
var len = details.length;
for (var i = 0; i < len;) {
var detail = {
dimension : details[i].dimension,
value : details[i].value
}
description.push(detail);
++i;
}
item.properties = description;
});
});
self.port.emit('getDimension');
self.port.on('dimension', function(response) {
var dimensions = eval('('+ response + ')');
for(var cont = 0, l = dimensions.length; cont < l; ++cont) {
table.append("<tr id=dimension"+cont+"><td>"+dimensions[cont]+"</td></tr>");
items.forEach( function(item) {
var prop = [];
prop = item.properties;
var lun = prop.length;
for( var p =0;p < lun;) {
if(item.properties[p].dimension == dimensions[cont]) { table.find('#dimension'+cont).append("<td>"+item.properties[p].value+"</td>");
}
else {
table.find('#dimension'+cont).append("<td> --- </td>");
}
++p; }
});
};
});
container.append(table);
});