Log JSON field when clicking on a table row - javascript

I am using Framework7 to build a mobile app. Using the popup and request features, I am dynamically building an html table with JSON data as follows:
//Do something when popup is opened
$$(document).on('popup:opened', '.popup-airconSearch', function (e) {
//Show preloader
app.preloader.show();
//Request json data from URL
app.request.json('my-URL', function (data) {
var tableHtml = '';
for(var i = 0; i < data.length; i+=1){
tableHtml+= '<tr><td class="numeric-only">' +data[i].brand+ '</td> <td class="numeric- only">' +data[i].model+ '</td></tr>';
}
//Add rows to HTML table
$$('.data-table #airconDatabase').html(tableHtml);
app.preloader.hide();
})
})
The JSON URL also includes an ID field and I am trying to log the ID of each entry when a table row is clicked. I have updated the above function with:
$$('.data-table #airconDatabase tr').on('click', e => {
var id = data[i].regnumber;
console.log (id);
})
However the console logs ID as underfined. If I change it to
var id = data[0].regnumber;
Then the first JSON entry regnumber field is logged to console no matter which table row is clicked. If I change it to
var id = data[1].regnumber;
Then the second JSON entry regnumber field is logged and so on.
Where am I going wrong?

My solution:
Firstly build the dynamic HTML table with a row ID from the JSON data:
tableHtml+= '<tr id="' +data[i].am_5_regnumber+ '"><td class..
Then get the row ID when a table row is clicked:
$$('.data-table #airconDatabaseTable tbody tr').on('click', function (e) {
var zaf = $$(this).closest('tr').attr('id');
console.log (zaf);
})
In addition to the above, I had to add an ID to the HTML table and not just the table body.

Related

How to access JSON data in another html page?

I am trying get request to fake jsonplaceholder api site. Also, I got the result and list placeholder/todos datas as its title on my HTML page. I want to click selected todo item and it will redirect another html page to list item details as id,userId,title,completed properties. But, I can redirect only id property, I can't redirect other properties.
success: function (e) {
let items=e;
for (let i = 0; i < items.length; i++) {
//console.log(jsonitem[i]);
$('#todos').append('<a class="todo-item" onclick="onItemClick(' +items[i].title
+ ')">' + items[i].title + '</a>')
console.log(items[i]);
}
},
function onItemClick(jsonitem){
window.document.location='./index3.html'+'?item='+jsonitem;
}
//another html page
$(document).ready(function(){
let items = document.location.search.replace(/^.*?\=/,'');
$("#txtDetail").html(items);
console.log(items);
})

JQGrid : How to get Selected Row ID of Custom "Delete" column

I follow up the sample code of JQGrid page (choose Navigator "Row Editing (New)" => "Custom Edit" on Left).
I try to display "Delete" column and I also follow up the following script on JQGrid page as well (choose Navigator "Live Data Manipulation" => "Delete Row" on Left).
$("#dedata").click(function(){
var gr = jQuery("#delgrid").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#delgrid").jqGrid('delGridRow',gr,{reloadAfterSubmit:false});
else alert("Please Select Row to delete!");
});
My problem is, gr is not return row_id value.
Do you know how to get selected row id ?
Here is my JQGrid script:
$("#UserListGrid").jqGrid({
... //Some above jqGrid options
/* Fill in column "Delete" */
gridComplete: function () {
var ids = jQuery("#UserListGrid").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
de = "<input style='height:22px;width:50px;' type='button' value='Delete' onclick=\"JQGridRemoveSelectedRow('UserListGrid');\" />";
jQuery("#UserListGrid").jqGrid('setRowData', ids[i], {
act: de
});
}
}
});
function JQGridRemoveSelectedRow(JQGridID) {
var gr = jQuery("#" + JQGridID).jqGrid('getGridParam', 'selrow');
alert(gr);
/* if (gr != null) jQuery("#" + JQGridID).jqGrid('delGridRow', gr, { reloadAfterSubmit: false });
else alert("Please Select Row to delete!");*/
if (gr != null)
alert(gr );
else
alert("Please Select Row to delete!");
}
I try to see gr, it returns value jqg1 , jqg2 , jqg3 but I would like to get Selected Row_Id.
First of all the values jqg1, jqg2, jqg3 are really rowids and jQuery("#delgrid").jqGrid('getGridParam','selrow') returns correct values. The rowid is by definition the value of id attribute on the corresponding row of the grid (id of <tr> element). jqGrid always assign id attribute to every row. See the picture. If you work with local data, then delGridRow will delete the row without any problems.
You wrote that you would like to use Email as rowid. Are the values from Email unique (it could be no two rows with the same email)? You can change your code to inform jqGrid to use the value from Email column as rowid. To do this you can just add key: true property in the definition of Email column of colModel.
Alternatively you can extend JSON data returned from the server and to include id property to it. You can use as the value of id property the email of the user or the UserId from the corresponding table of the database, which you use on the backend. You are free to define, which information (which value) better identify users.

passing value to a different webpage form

I'm trying to learn to make a webapp using JavaScript along side with nodejs. I'm all out of ideas and have no clue if im doing this correctly. So what im trying to do is when a user clicks on a row of a the dynamically created table it opens up a new html page with a bunch of form inputs already filled in with the values in a json. Right now I have it that when I click on the table row I can get the Id chosen and as a test i want to load it in to a input field but im getting it as undefined
a good portion of the table creating function with the fillform function
for (i = 0; i < attendee.length; i++) {
var tr = document.createElement('TR');
if(i % 2 == 0)
{
tr.bgColor = '#E9F2F5';
}
for (var j = 0; j < attendee[i].length; j++) {
var td = document.createElement('TD');
/* if (j != 0) {
td.setAttribute('contenteditable', 'true');
}*/
td.appendChild(document.createTextNode(attendee[i][j]));
tr.appendChild(td);
var currentRow = table.rows[i];
var createClickHandler =
function(tr)
{
return function() {
var cell = tr.getElementsByTagName("td")[0];
var id = cell.innerHTML;
fillForm(id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
tableBody.appendChild(tr);
}
myTableDiv.innerHTML = "";
myTableDiv.appendChild(table);
}
// this function is included in the html page as a onload function
function fillForm(id)
{
window.open("/populatedForm.html");
document.getElementById("id").value = id;
console.log(id);
}
Part of the html input I want to fill out.
<div class=container2>
<form method="PUT" action="/process-form" enctype="multipart/form-data" autocomplete="off">
<fieldset>
<label>
ID<br/>
<input id="id" name="id" type="text" value=" " required/>
</label>
<br/>
This is how my table looks like
And this is how the input looks like when I click on a row in the table. It opens the new html page but the input is set to undefined. I havent done the rest since I cant get id to work.
Any advice would be great! Thank you!
I am going to further answer this down here as it is too long for me to post in the comments.
Once you figure out how to do routing you won't want to do it another way, here is a great resource http://expressjs.com/en/guide/routing.html . Look at the route parameters section.
So what I would do is have a route like /populatedForm/:id. In express it will look something like this.
app.get('/populatedForm/:id', function(req, res) {
res.send(req.params);
});
req.params will grab the id you want to grab, and then where it says res.send() is where you can handle all the business logic from that route. That is where I'd make a call out to the database to grab all the information for that ID, and then send it as a json, then handle the JSON on your front end.
it'd look something like this
app.get('/populatedForm/:id', function(req, res) {
var myJson = getIdAndOtherInfoFromDatabase(req.params);
res.send(myJson);
});
Then you can handle all of it on the front end via JSON. I would google around a bit about this stuff if you get confused or stuck.

Dynamically add rows into a table using data from another table-jQuery

I have two table on my page like the picture shown here.
What I want to do is:
select rows in the Source Table
read the data in ID field, Name field from the Source Table, and also the value of radio button.
Form these data as rows of Target Table and append these rows into Target Table.
Now Im using two arrays to store the ID and Name that read from Source Table, but im a bit confused about how to form a row for the Target Table.
$('#btnLinkCase').click(function (event) {
var caseID = $('#caseID').text();
var linkedIDArr = []; //array list for selected id
var linkedNameArr = []; //array list for selected name
$('#linkCaseTable tbody tr td:nth-child(2)').each(function (index, el) { //store each paire of <tr> into array
linkedIDArr.push(el);
});
$('#linkCaseTable tbody tr td:last-child').each(function (index, el) { //store each paire of <tr> into array
linkedNameArr.push(el);
});
$.each(linkedCaseIDArr, function (index, val) {
//whats next?
});
});
Please see all source code here
Any ideas of doing this? Thanks in advance
Edit:
If multiple rows are selected they will use the same value from the radio button. eg: two rows are selected and "Type 1" is checked. In target table, their relationship all are "Type 1". I hope I have explained myself..
Try:
$('button').click(function (event) {
$("#sourceTable tr:gt(0)").each(function(){
var th = $(this);
console.log("dfg")
if($(th).find("input[name='link-cbx']").is(":checked")){ //assuming ids are unique remove condition if you do notwant so
var id = $(th).find("td:eq(1)").text();
var name = $(th).find("td:eq(7)").text();
var type = "Type "+$("input[name='linkType']:checked").val();
if($("#targetTable:contains('"+id+"')").length < 1){
$("#targetTable").append("<tr><td>"+id+"</td><td>"+name+"</td><td>"+type+"</td></tr>");
}
}
});
});
Updated fiddle here.

How to construct the id of an element and perform actions on it in JQuery?

I have a button in my table row which is having an id btn_number_$i. On clicking the button I want to show the table row having id row_$i, which is initially hidden.
Here is my PHP code to create the two table rows:
echo "<tr><td>"."<button id= \"btn_number_$i\" class='btn info toggler' >Info <i class='icon-arrow-down'></i></button>"."</td></tr>";
echo "<tr id='row_$i' class='info_row'><td>Hello There!!</td></tr>";
And below is my jQuery code.
I am trying to construct the similarly named row id and perform .show on it. But I am not getting the desired result.
$(function () {
$('.info_row').hide(); // first I need to hide all the second rows.
$('.toggler').click(function () {
var currentId = $(this).attr('id');
console.log(currentId);
var lastChar = currentId.substr(currentId.length - 1); //Herein I am trying to extract the last character from btn_number_$i which is $i and then appending it with 'row_'
var rowId = 'row_' + lastChar;
console.log(rowId); // I am able to get the current value in console log.
$('#rowId').show(); // But even after all that i am not able to show the element.
});
});
Any help will be thankfully appreciated.
You are not using the variable rowId containing id you constructed but using rowId a string literal. The selector you have will be looking element with id = rowId
Change
$('#rowId').show();
To
$('#' + rowId).show();

Categories

Resources