to search through the json object and obtain the data - javascript

I have my JSON data in a table, I have to search a particular id and display the data of that id.
$(document).ready(function(){
$.getJSON("data/db.json", function(data){
var dbdata = "";
$.each(data, function(key,value){
dbdata += '<tr>';
dbdata += '<td>' + value.userId + '</td>';
dbdata += '<td>' + value.id + '</td>';
dbdata += '<td>' + value.title + '</td>';
dbdata += '<td>' + value.completed + '</td>';
dbdata += '</tr>';
})
$('#datainfo').append(dbdata);
})
})
and when I type the id in the input filed it must display the data of that id.
Enter the Id:
Search
this is code for displaying the JSON data in a table. I want to search the id so that I get the data of the id.
please provide the function that does search through the JSON object!
Thank You.

$(document).ready(function(){
$.getJSON("data/db.json", function(data){
var dbdata = "";
$.each(data, function(key,value){
if ( value.id == "user_search_key"){
dbdata += '<tr>';
dbdata += '<td>' + value.userId + '</td>';
dbdata += '<td>' + value.id + '</td>';
dbdata += '<td>' + value.title + '</td>';
dbdata += '<td>' + value.completed + '</td>';
dbdata += '</tr>';
}
})
$('#datainfo').append(dbdata);
})
})

Related

Making text in a cell a button javascript

is there anyway to make this extra td a button so that every "show" is clickable?
$(document).ready(function(){
$.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data){
var custData = '';
$.each(data, function(key, value){
custData += '<tr>';
custData += '<td>' +value.name+'</td>';
custData += '<td>' +value.address+'</td>';
custData += '<td>' +value.cityStateZip+'</td>';
custData += '<td>' +value.latLang+'</td>';
custData += '<td>' +(value.image || "No image available")+'</td>';
custData += '<td>' +"show"+ '</td>'; // this is what I need a button
custData += '</tr>';
});
I'm worried that I messed up by adding that extra column alongside the others being created with json data, but I'm not sure how else to add a button for every row.
I'm not sure I understand your question. But here is an example for you that prints row numbers when clicked 'show'.
function printRowNumber(row) {
alert('Row:' + row);
return false;
}
$(document).ready(function() {
const appDiv = document.getElementById('app');
$.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data) {
var custData = '';
$.each(data, function(key, value) {
custData += '<tr>';
custData += '<td>' + value.name + '</td>';
custData += '<td>' + value.address + '</td>';
custData += '<td>' + value.cityStateZip + '</td>';
custData += '<td>' + value.latLang + '</td>';
custData += '<td>' + (value.image || "No image available") + '</td>';
custData += '<td>' + '<a href="javascript:void" onClick=printRowNumber(' + key + ')>show</a>' + '</td>'; // this is what I need a button
custData += '</tr>';
});
appDiv.insertAdjacentHTML('beforeend', '<table>' + custData + '</table>');
})});
If you want to use button instead of 'show' you can replace a tag with button.
custData += '<td>' +'<button onClick=printRowNumber('+key+')>show</button>'+ '</td>';

Dynamic Row addition to the Table

I want to add Array elements to the table.
Array elements are dynamic coming from the database. And i am creating the Row for adding the one row from the generated data and appending rowAfter to add the other array elements
Here is the code i have written -
var rowSpan = 0;
var rowSpan1 = 0;
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
var QuantityArray = data[element].quantity.split(',');
var ChemistArray = data[element].Retailername.split(',');
var PobArray = data[element].Pob.split(',');
rowSpan = productsArray.length;
rowSpan1 = ChemistArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
row += '<td>' + QuantityArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td><td>' + QuantityArray[i] + '</td>';
}
}
for (var k = 0; k < rowSpan1; k++) {
if(k == 0) {
row += '<td>' + ChemistArray[k] + '</td>';
row += '<td>' + PobArray[k] + '</td>';
} else {
rowAfter += '<td>' + ChemistArray[k] + '</td><td>' + PobArray[k] + '</td> </tr>';
}
}
row +=
'<td rowspan="'+rowSpan1+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan1+'">' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row+rowAfter);
So as per the code I can finely display ProductArray and Quantity Array
And But i am not able to display the Chemist array after one another.
In the above Image i want to display data( Kapila and Kripa below the Chemist column) Some where making issue with tr and td.
Any help would really appreciated.
Data is a JSON Response -
In my case, ChemistArray(Retailername in response) contains 4 names and POBArray 4 values.
You need to add an empty <td></td> as a "placeholder".
for (element in data) {
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
// only add '<tr>' if row !== 0
// It's because for the first row, we already have an open <tr> tag
// from the line "content += '<tr>' + date + doctorName;"
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
// only add "locations + area + '</tr>'" if it is the first row
// because locations and area will span the whole column
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>'; is just a short-hand for
content += '<td>';
if (productsArray[row]) {
content += productsArray[row];
} else {
content += '';
}
content += '</td>';
If there is item in the productsArray[row], let's say productsArray[0], which is 'Sinarest', then productsArray[row] would be truthy. Else, if there is no more products in the array, such as productsArray[3] will gives us undefined, which is a falsy value and the corresponding conditional will be ran.

how to assign multiple values to a button when loading table using javascript and json

In the below code i have used a json array(pedingPLT) to load data to below html table. here each an every table data has got a single value. in a particular table data i have included an button.so is there any possibility to assign multiple values to the button (*********), i mean by using an array. kindly help me
function TSC_document_status_list_table_for_tsc_portal() {
var tableData;
$.post("model/tscAdminView.php", {action: 'TSC_document_status_list_table_for_tsc_portal'}, function (e) {
if (e === undefined || e.length === 0 || e === null) {
tableData = '<tr class="error"><td colspan="4"> No Data Found in database </td></tr>';
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
} else {
$.each(e, function (index, pedingPLT) {
index++;
tableData += '<tr>';
tableData += '<td>' + index + '</td>';
tableData += '<td>' + pedingPLT.document_id + '</td>';
tableData += '<td>' + pedingPLT.tsc_accepted_Or_Created_date +'</td>';
tableData += '<td>' + pedingPLT.total_allocated_days + ' days' + '</td>';
tableData += '<td>' + pedingPLT.Expired_date + '</td>';
tableData += '<td> <button class="btn btn-sm btn-alt m-r-5 delete_selected_employee" value="' + ******** + '"><i class="fa fa-trash-o fa-lg"></i> </button>' + pedingPLT.total_quantity +'</td>';
tableData += '<td>' + pedingPLT.Completed_phone_list + '</td>';
tableData += '<td>' + pedingPLT.peding_phone_list + '</td>';
tableData += '</tr>';
});
//Load Json Data to Table
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
}
}, "json");
}
The value attribute of button is of type "text" (source), so it's not possible to add multiple values to it.
That said, you are free to stringify a JSON-string in it as value, and parse it when you need it:
JSON.stringify()
(method documentation: JSON.stringify)
You can use data-value attribute in the button and put the json string in the data-value attribute.
function TSC_document_status_list_table_for_tsc_portal() {
var tableData;
$.post("model/tscAdminView.php", {action: 'TSC_document_status_list_table_for_tsc_portal'}, function (e) {
if (e === undefined || e.length === 0 || e === null) {
tableData = '<tr class="error"><td colspan="4"> No Data Found in database </td></tr>';
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
} else {
$.each(e, function (index, pedingPLT) {
var button_data_value = '{"document_id" : pedingPLT.document_id , "total_days" : pedingPLT.total_allocated_days }';
index++;
tableData += '<tr>';
tableData += '<td>' + index + '</td>';
tableData += '<td>' + pedingPLT.document_id + '</td>';
tableData += '<td>' + pedingPLT.tsc_accepted_Or_Created_date +'</td>';
tableData += '<td>' + pedingPLT.total_allocated_days + ' days' + '</td>';
tableData += '<td>' + pedingPLT.Expired_date + '</td>';
tableData += '<td> <button class="btn btn-sm btn-alt m-r-5 delete_selected_employee" data-value= "'+JSON.Stringify(button_data_value)+'"><i class="fa fa-trash-o fa-lg"></i> </button>' + pedingPLT.total_quantity +'</td>';
tableData += '<td>' + pedingPLT.Completed_phone_list + '</td>';
tableData += '<td>' + pedingPLT.peding_phone_list + '</td>';
tableData += '</tr>';
});
//Load Json Data to Table
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
}
}, "json");
}

Javascript / jQuery changing cell of a table based on the value

Hi i have a javascript function that take the contents of a JSON file and the puts it in to a table, here is the code.
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
However what i need is to some formatting via if statements so for example
normally i would use something like the badly put together bunch of If statements.
if (Person.clock !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.Off !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
if (Person.on !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.out !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
However i am struggling to find the best way of putting what i already have with the function for creating the table and putting the formatting from the If statements together
what would be the best way to do this?
Why not add a class to each such case. something like this:
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td class="'+(Person.clock? 'hasClock' : '') +'">' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
$(content).appendTo("tbody");
console.log(Person);
});
});
and then add a class to your css:
.hasClock{
background-color :lime;
}
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td class="op ' + Person.Op + '">' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
Add class to your td's with the value. If you have definite values coming up, then you can create css selectors for that with the CSS properties you want.
Suppose you had value of op as someOpValue
You could write your css like foloowing.
td.op.someOpValue{
background : red;
}

funny behavior of jquery code

Funny thing is that if i delete the comment for alert(data[i].id) the code works. As it is in the example, the string is not concatenated thus i have no options in the select box. Hints? Help?
Re-edited so that you guys can see the whole method
function socialbookmarksTableData(data)
{
var toAppend = '';
var bookmarkingSites = '';
$.getJSON("php/socialbookmark-get-bookmarking-sites.php",function(data){
for(var i = 0; i < data.length; i++){
//alert( data[i].id);
bookmarkingSites += '<option value = "' + data[i].id + '">' + data[i].title + '</option>';
}
});
$.each(data.results, function(i, id){
if(i%2 == 1)
toAppend += '<tr class="first">';
else
toAppend += '<tr class="second">';
if(data.results[i].status == "PENDING" || data.results[i].status == "POSTED")
toAppend += '<td><span class="approved">' + data.results[i].status + '</span></td>';
else
toAppend += '<td>' + data.results[i].status + '</td>';
toAppend += '<td><select name="sb2" id="sb2">'+
'<option value="'+ data.results[i].bookmark +'">' + data.results[i].bookmark +'</option>' +
bookmarkingSites + '</select></td>';
toAppend += '<td>' + data.results[i].user + '</td>';
toAppend += '<td>' + data.results[i].link + '</td>';
toAppend += '<td>Some Article</td>';
toAppend += '<td>' + data.results[i].title + '</td>';
toAppend += '<td>' + data.results[i].description + '</td>';
toAppend += '<td>' + data.results[i].tags + '</td>';
toAppend += '<td>' + data.results[i].date + '</td>';
toAppend += '<td><div class="actions">';
toAppend += '<ul><li><input class="radio" name="input" type="checkbox" value="' + data.results[i].id + '" /></li>';
toAppend += '<li><a class="action1" href="#">1</a></li>';
toAppend += '<li><a class="action4" href="#">4</a></li></ul></div></td></tr>';
});
$("#searchTable tbody").append(toAppend);
}
One is reason: When you enclose strings in single quotes, you don't have to escape the double quotes (the backslash does not work as escape operate here anyway I think). So this:
bookmarkingSites += '<option value = \"' + data[i].id + '\">' + data[i].title + '</option>';
Should be:
bookmarkingSites += '<option value="' + data[i].id + '">' + data[i].title + '</option>';
The other reason: your code between <some more code> is not in the callback function, but you try o access data from the function (data and bookmarkingSites). Put all the HTML generation code inside the callback function.
Ah so it is an other data ;) Anyway you cannot access bookmarkingSites in your code because it does not yet exists when the code is executed. Try this:
function socialbookmarksTableData(data)
{
$.getJSON("php/socialbookmark-get-bookmarking-sites.php",function(bookmarks){
var toAppend = '';
var bookmarkingSites = '';
for(var i = 0; i < bookmarks.length; i++){
//alert( bookmarks[i].id);
bookmarkingSites += '<option value = "' + bookmarks[i].id + '">' + bookmarks[i].title + '</option>';
}
$.each(data.results, function(i, id){
if(i%2 == 1)
toAppend += '<tr class="first">';
else
toAppend += '<tr class="second">';
if(data.results[i].status == "PENDING" || data.results[i].status == "POSTED")
toAppend += '<td><span class="approved">' + data.results[i].status + '</span></td>';
else
toAppend += '<td>' + data.results[i].status + '</td>';
toAppend += '<td><select name="sb2" id="sb2">'+
'<option value="'+ data.results[i].bookmark +'">' + data.results[i].bookmark +'</option>' +
bookmarkingSites + '</select></td>';
toAppend += '<td>' + data.results[i].user + '</td>';
toAppend += '<td>' + data.results[i].link + '</td>';
toAppend += '<td>Some Article</td>';
toAppend += '<td>' + data.results[i].title + '</td>';
toAppend += '<td>' + data.results[i].description + '</td>';
toAppend += '<td>' + data.results[i].tags + '</td>';
toAppend += '<td>' + data.results[i].date + '</td>';
toAppend += '<td><div class="actions">';
toAppend += '<ul><li><input class="radio" name="input" type="checkbox" value="' + data.results[i].id + '" /></li>';
toAppend += '<li><a class="action1" href="#">1</a></li>';
toAppend += '<li><a class="action4" href="#">4</a></li></ul></div></td></tr>';
});
$("#searchTable tbody").append(toAppend);
});
}
What you've got is a classic race condition. The getJSON code is making an asynchronous call. When you have the alert in there the code below the getJSON call is executed before the call returns from the callback. Without the alert, it's being executed after the callback. This is actually a lucky occurence as you can't be guaranteed that it will happen that way. You should put all the code that relies on the data returned from the getJSON call into the callback so you can guarantee that the data is returned before using it.
var bookmarkingSites = '';
$.getJSON("php/socialbookmark-get-bookmarking-sites.php",function(data){
for(var i = 0; i < data.length; i++){
//alert( data[i].id);
bookmarkingSites += '<option value = "'
+ data[i].id + '">'
+ data[i].title + '</option>';
}
<some more code>
toAppend += '<td><select name="sb2" id="sb2">'
+ '<option value="'+ data.results[i].bookmark +'">'
+ data.results[i].bookmark +'</option>'
+ bookmarkingSites + '</select></td>';
<some more code>
}); // end of JSON call/callback
From the code provided it looks like you do the JSON call and the callback function appends to the bookmarkingSites variable. so far so good.
The code that the arrow points to is outside the callback function and will run before the JSON callback is called, therefore bookmarkingSite will be empty string and there will be no options in the select box.
Wouldn't the code to build the option tag also go in the callback or be in a function called by the callback?

Categories

Resources