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
Related
I'm looping through all the html tags in an html-file, checking if those tags match conditions, and trying to compose a JSON-object of a following schema:
[
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' }
]
But I'd like to create the new entry only for elements, classed "header", all the other elements have to be added to earlier created entry. How do I achieve that?
Current code:
$('*').each((index, element) => {
if ( $(element).hasClass( "header" ) ) {
jsonObject.push({
title: $(element).text()
});
};
if( $(element).hasClass( "date" )) {
jsonObject.push({
date: $(element).text()
});
}
//links.push($(element))
});
console.log(jsonObject)
Result is:
{
title: 'TestA'
},
{ date: '10.10.10' },
{
title: 'TestB'
},
{ date: '10.10.11' }
I'd like it to be at this stage something like:
{
title: 'TestA'
,
date: '10.10.10' },
{
title: 'TestB'
,
date: '10.10.11' }
UPD:
Here's the example of HTML file:
<h1 class="header">H1_Header</h1>
<h2 class="date">Date</h2>
<p>A.</p>
<p>B.</p>
<p>С.</p>
<p>D.</p>
<a class="source">http://</a>
<h1 class="header">H1_Header2</h1>
<h2 class="date">Date2</h2>
<p>A2.</p>
<p>B2.</p>
<p>С2.</p>
<p>D2.</p>
<a class="source">http://2</a>
Thank you for your time!
Based on your example Html, it appears everything you are trying to collect is in a linear order, so you get a title, date, body and link then a new header with the associated items you want to collect, since this appears to not have the complication of having things being ordered in a non-linear fasion, you could do something like the following:
let jsonObject = null;
let newObject = false;
let appendParagraph = false;
let jObjects = [];
$('*').each((index, element) => {
if ($(element).hasClass("header")) {
//If newObject is true, push object into array
if(newObject)
jObjects.push(jsonObject);
//Reset the json object variable to an empty object
jsonObject = {};
//Reset the paragraph append boolean
appendParagraph = false;
//Set the header property
jsonObject.header = $(element).text();
//Set the boolean so on the next encounter of header tag the jsobObject is pushed into the array
newObject = true;
};
if( $(element).hasClass( "date" )) {
jsonObject.date = $(element).text();
}
if( $(element).prop("tagName") === "P") {
//If you are storing paragraph as one string value
//Otherwise switch the body var to an array and push instead of append
if(!appendParagraph){ //Use boolean to know if this is the first p element of object
jsonObject.body = $(element).text();
appendParagraph = true; //Set boolean to true to append on next p and subsequent p elements
} else {
jsonObject.body += (", " + $(element).text()); //append to the body
}
}
//Add the href property
if( $(element).hasClass("source")) {
//edit to do what you wanted here, based on your comment:
jsonObject.link = $(element).next().html();
//jsonObject.href= $(element).attr('href');
}
});
//Push final object into array
jObjects.push(jsonObject);
console.log(jObjects);
Here is a jsfiddle for this: https://jsfiddle.net/Lyojx85e/
I can't get the text of the anchor tags on the fiddle (I believe because nested anchor tags are not valid and will be parsed as seperate anchor tags by the browser), but the code provided should work in a real world example. If .text() doesn't work you can switch it to .html() on the link, I was confused on what you are trying to get on this one, so I updated the answer to get the href attribute of the link as it appears that is what you want. The thing is that the anchor with the class doesn't have an href attribute, so I'll leave it to you to fix that part for yourself, but this answer should give you what you need.
$('*').each((index, element) => {
var obj = {};
if ( $(element).hasClass( "header" ) ) {
obj.title = $(element).text();
};
if( $(element).hasClass( "date" )) {
obj.date = $(element).text()
}
jsonObject.push(obj);
});
I don't know about jQuery, but with JavaScript you can do with something like this.
const arr = [];
document.querySelectorAll("li").forEach((elem) => {
const obj = {};
const title = elem.querySelector("h2");
const date = elem.querySelector("date");
if (title) obj["title"] = title.textContent;
if (date) obj["date"] = date.textContent;
arr.push(obj);
});
console.log(arr);
<ul>
<li>
<h2>A</h2>
<date>1</date>
</li>
<li>
<h2>B</h2>
</li>
<li>
<date>3</date>
</li>
</ul>
Always use map for things like this. This should look something like:
let objects = $('.header').get().map(el => {
return {
date: $(el).attr('date'),
title: $(el).attr('title'),
}
})
I'm using DataTables library for creating table with "download" button.
At the first row the button is working, but at the rest of the rows is not working (I'm using loop to enter the data to the table).
what am i doing wrong?
JS Code:
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
number = childData.Number;
table.row.add( [
number,
"<button id='script'>Download Files</button>"
] ).draw( false );
button = document.getElementById('script');
button.onclick = function(){ myScript(number)};
});
You create many buttons with the same id, so document.getElementById('script'); will always return the same first element with this id.
You can try something like this:
snapshot.forEach(function(childSnapshot, i) {
var childData = childSnapshot.val();
number = childData.Number;
table.row.add( [
number,
`<button id='script${i}'>Download Files</button>`
] ).draw( false );
button = document.getElementById(`script${i}`);
button.onclick = function(){ myScript(number)};
});
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.
[![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
I am working on a wordpress blog with a custom metabox on the edit page of each post.
This metabox consists of table with each row containing image src selected from media library.
Now every new row added has an id :
row 1 : img_metabox_src_0
row 2 : img_metabox_src_1
row 3 : img_metabox_src_2
Table headers goes like :
----Image < img >------ |------- URL (Input textbox)------ | -------- Select Image (Input submit)------ | -----Delete Image (Input submit)--------
Now,
On click on "Select Image" on any row, I retrieve the row index from jquery, and then send : "img_metabox_src_"+index to file_frame.on( 'select', function() for url update.
i.e.
jQuery('tr #select_image').off().on('click', function( event ){
event.preventDefault();
var row_index = jQuery(this).closest('tr').index();
var id = "img_metabox_src_" + row_index;
//******** 1 ***********
console.log('row_index');
console.log(row_index);
console.log(id);
console.log(jQuery('#' + id));
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media({
title: "Select/Upload Image",
button: {
text: "Select",
},
library : { type : 'image'},
multiple: false
});
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
// "mca_features_tray" is the ID of my text field that will receive the image
// I'm getting the ID rather than the URL:
// but you could get the URL instead by doing something like this:
//******** 2 ***********
console.log(id);
console.log(jQuery('#' + id));
jQuery('#' + id).attr('value',attachment.url);
id = null;
});
Now,
Case 1 : When I FIRST click with row index3, the URL updates on img_metabox_src_3.
Case 2 : But after that whichever row i click, the url updates on img_metabox_src_3.
Also on adding logs, I get
(for Case 2, say I clicked row index 1) :
//******** 1 ***********
row index : 1
id : img_metabox_src_1
//******** 2 ***********
id : img_metabox_src_3
i.e. inside file_frame.on( 'select', function() {,
the ID value changes to first clicked value.
Please help on how to pass updated row index/id to the select function
Thanks, I used global concept :
function set_row_index (ind){
row_index = ind;
}
function get_row_index(){
return row_index;
}
jQuery(document).ready(function(){
jQuery('tr input.select_media_library').off().on('click', function( event ){
event.preventDefault();
var index = jQuery(this).closest('tr').index();
**set_row_index(index);**
.
.
.
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
**index = get_row_index();**
var id = "img_src_" + index;
jQuery('#' + id).attr('value',attachment.url);
});
file_frame.open();
});