When Pushing elements into array, same elements are repeated replacing previous one - javascript

I'm creating an Dynamic form in angular js and when I'm adding new input fields as table row,and when pushing these objects into an array, previous element is replaced with copy of new element. Keys are same but values are different and also adding 'id' key before pushing into array.
JS
else if (el.type === 4) { //table
var x = 0;
$scope.row = []; //to store KEY OF table
$scope.thead = []; //store the heading of the table | also to make row structure
$scope.myFm[el.value] = []; //store row of table [ INVOICE ] myFm.invoice
$scope.colInput = {}; //values of input of each row
$scope.colInput.id = 0;
$scope.rowIndex = 0;
//iterate over column_heading
el.column_heading.forEach(function(elem) { //objects in column_heading
$scope.row[x] = elem.val; //the object with key names of row
$scope.thead.push(elem); //column headings
x++;
})
//pusing each row to myFm[el.value] | invoice
$scope.addNew = function(rowObj) {
// $scope.rowIndex++;
console.log('ROW ', rowObj);
rowObj.id = $scope.rowIndex;
$scope.myFm[el.value].push(rowObj);
console.log("Invoice", $scope.myFm[el.value]);
$scope.rowIndex++;
console.log("ROW", rowObj);
}
var row = "<tr ng-repeat='r in myFm." + el.value + " track by id' ><td ng-repeat='i in row'><input ng-model='colInput[i]' class='form-control' placeholder='Enter {[{ i }]}'></td></tr>"
item = "<label>" + el.heading + "<button ng-click='addNew(colInput)' class='m-l-lg btn font-bold'>ADD NEW</button></label> <table class='table'><thead><th ng-repeat='th in thead'>{[{ th.name }]}</th><thead>" + "<tbody>" + row + "</tbody><table>";
}
return item
}
// adding each element from list to DOM. $compile is needed to add the modified element to DOM
$scope.data.forEach(function(el) { //traversing over json object from the server
var item = verifyItem(el);
var linkFn = $compile(item);
var content = linkFn($scope);
element.append(content);
});
// adding the submit button to DOM
var linkFn = $compile('<button type="submit" ng-click="submitFm()" class="m- t-lg m-b-lg btn btn-danger">Submit </button>');
var content = linkFn($scope);
element.append(content);
When i',m passing 'colInput' to the 'addNew' function, and adding 'id' key each time i push new object to array '$scope.myFm[el.value]', the duplicates are being created ie: the newly added is replacing the previous objects, hence i cant 'ng-repeat' it by 'track by id'.
CONSOLE
Invoice Array [ Object, Object, Object ]
these three objects have values of last pushed object.
how do i fix it.

Related

update prices in text after deleting items from button in inner html

The div tags are created inside this const and I have used a delete function to delete items from order page. I want to update prices after deletion and updating in text displaying totalprice.
total_price = total_price + parseInt(item.prisinklmoms);
// Create a row for the item in view
const order_item = document.createElement('div');
order_item.className = `ordered_item`;
order_item.innerHTML = `<div class="product-name">${item.namn}</div>
<div class="product-percentage">${item.alkoholhalt}</div>
<div class="product-price">${item.prisinklmoms}</div>
<button id="div-button" onclick="delOrderlist(this)">Del</button>`;
orderContainer.appendChild(order_item);

How to extract all td's text content from an element in the array?

How to extract td's text content and store each one into an array from another array that contain the following contents:
//create two element in the array, that store a string containing html code
tablecontentArray[0] = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`"
tablecontentArray[1] = "`<tbody><tr><th>Title 5</th><th>Title 6</th></tr><tr><td>Fruit 5</td><td>Fruit 6</td></tr><tr><th>Title 7</th><th>Title 8</th></tr><tr><td>Fruit 7</td><td>Fruit 8</td></tr></tbody>`"
//loop to extract the td text content from the each element of the tableContentArray and store it into extractedTdArray
extractedTdArray = [];
var str = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`"
var extractedTdArray = str.split("<td>")
.filter(function(v){ return v.indexOf('</td>') > -1})
.map( function(value) {
return value.split("</td>")[0]
})
console.log(extractedTdArray)
First you split up the string into arrays by <td> you get
0:"`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr>"
1:"Fruit 1</td>"
2:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>"
3:"Fruit 3</td>"
4:"Fruit 4</td></tr></tbody>`"
Then you get the elements that have the closing </td> in with the filter
0:"Fruit 1</td>"
1:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>"
2:"Fruit 3</td>"
3:"Fruit 4</td></tr></tbody>`"
then you split it by the </td> and get the first element. we already split by <td> so we know that from the beginning is the info we want to the </td>.
["Fruit 1", "Fruit 2", "Fruit 3", "Fruit 4"]
setting one table and push
var extractedTdArray = [];// create result array
// loop across html strings
$.each(tablecontentArray, function (key, table) {
$('#table').html(table);//create html table
// loop across the created table td's
$.each($('#table').find('td'), function (key2, td) {
var tdVal=$(this).text();// td value
//push to array
extractedTdArray.push(tdVal);
});
});
});
setting multiple tables and map
// set tables
$.each(tablecontentArray, function (key, table) {
$('#table' + key).html(table).addClass('table');
});
// map td
var extractedTdArray = $('.table tr:has(td)').map(function (i, v) {
return $(this).text();
}).get();

Jquery Datatables : How to get row.data when click the the button in one column?

[![enter image description here][1]][1]i have a nested table , I want to having button to generate the row data to info.php by post method (looks like info.php?user = data[0] & key2 = data2) in one column for each row ,
I have one button but I need one button and perform some MySql when they are clicked to get the row data .
when click the button will get to every columns data in the row and post these data to info.php and view in popup window,
How can I perform post the row data in the nested datatable to other php using the button?
my code
click the button ,cannot get the row data ?
$('#example tbody').on( 'click', 'button', function () {
var index = $(this).closest('tr').index();
var data = table.row( $(this).parents('tr') ).data();
alert("References is "+ data[0] +"and section is "+ data[ 1 ]+ " and Stature Titles is "+data[2] );
} );
-UPDATED
just add class for button class='button-info'
columns:[
{ data:'name' },
{ data:'position' },
{ data:'salary' },
{
"targets": -1,
"data": null,
"defaultContent": "<button class='button-info'>Click Me!</button>"
}
]
first assign index value for every parent row
$("table tbody tr").each(function(index) {
$(this).attr('index', index);
})
then add new event for click event of that button and get the parent tr index
just get the index of your selected parent row using data attribute "index" added above
var parent = $(this).closest('table').parents('tr').index();
var parentIndex = $('tbody tr:nth-child('+(parent)+')').attr('index');
and to get your current row in nested data
var index = $(this).closest('tr').index();
so this is the final
$('table').on( 'click', 'td .button-info', function () {
var parent = $(this).closest('table').parents('tr').index();
var parentIndex = $('tbody tr:nth-child('+(parent)+')').attr('index');
var currentIndex = $(this).closest('tr').index();
var data = sections[parentIndex][currentIndex];
console.log(data);
return;
window.open("/info.php?name=" + data.name + "&sal=" + data.salary);
} );
See this updated JSFiddle

How retrieve details of table element clicked?

I have a table and I want retrieve a item details of a element that i sesect:
var tableArtConNom=sap.ui.core.Core().byId("artSnzNomDetail").byId("tableArtConNom");
tableArtConNom.attachItemPress(this.handleRowPress);
tableArtConNom.setModel(new sap.ui.model.json.JSONModel(p_oDataModel));
tableArtConNom.destroyColumns();
tableArtConNom.removeAllColumns();
console.log(tableArtConNom.getColumns());
for(var i=0; i<tableArtConNom.getModel().getProperty("/cols").length; i++){
tableArtConNom.addColumn(new sap.m.Column("colonna"+i, { header: new sap.m.Label({ text: tableArtConNom.getModel().getProperty("/cols")[i] })}));
}
tableArtConNom.destroyItems();
tableArtConNom.removeAllItems();
tableArtConNom.bindAggregation("items", "/items", new sap.m.ColumnListItem({
cells: tableArtConNom.getModel().getProperty("/cols").map(function (colname) {
return new sap.m.Label({ text: "{" + colname + "}" });
}),
type:"Navigation"
}));
if(this.byId("idCodNomDog").getProperty("text")!=""){
var buttonAccept=this.byId("idButtonAccept");
buttonAccept.setProperty("visible", true);
}else{
var buttonAccept=this.byId("idButtonAccept");
buttonAccept.setProperty("visible", false);
}
tableArtConNom.setModel(new sap.ui.model.json.JSONModel(p_oDataModelFull), "fullDataModel");
},
To do it I capture the press event but I find only a number of item:
//IF CLICK ON ROW
handleRowPress : function(evt){
var selectedRowNum = evt.getSource().indexOfItem(evt.getParameter("listItem"));
console.log(selectedRowNum);
},
How can I print the other detailx (for example the content of a column?)
p.s. I can't parse the model of all my rows because in the table I filter the data and the index that i clicked not match by the position in the total model.
in your event handler, use :
var oItem = evt.getParameter("listItem").getBindingContext().getObject();
//NB: if using standard sap.ui.table.Table, use:
//var oItem = evt.getSource().getBindingContext().getObject();
console.log(oItem); //prints the JSON for your selected table row

How can I put dropdowns in cells of jQuery's Flexigrid?

I need to put dropdowns in a cell of my jQuery Flexigrid for the user to change the data in Flexigrid own. How do I do this?
I need only knowing how to put the dropdowns in cells.
You can put any HTML object in a Flexigrid.
function Retornaddl()
{
string linha = "<select class='inputlogininterno' id='resultadolista' name='resultadolista' style='width:150px;'><option value=''>Escolha...</option></select>";
return linha;
}
var jsonData = new
{
page = pageIndex,
total = count,
rows = (
from item in pagedItems
select new
{
id = item.ID,
cell = new string[] {
item.ID.ToString(),
Retornaddl()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
You can't. But you can make an edit button in the grid and display your edit stuff in a floting div.

Categories