Styling JSON with jQuery - javascript

I have a JSON value that has multiple values separated by a comma. Is there a way to have that rendered in the dom as a selection dropdown input?
Here is a more detailed view of my markup.
HTML
<h1>JSON Grid Edit</h1>
<table cellpadding="0" cellspacing="0" border="0" class="dt display" id="json-table-edit" contenteditable="true" onKeyUp="editValue(this.id);">
<thead>
<tr>
<th width="25%">Setting</th>
<th width="75%">Value</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
</tfoot>
</table>
JSON
{
"allconfig": {
"card.inserted": {
"value": "Inserted, Not Inserted",
},
"card.cisproc": {
"value": "Processed",
}
}
}
JQUERY
$.getJSON('json/ione-edit.json', function (data) {
var newJson = [];
var myJson = data;
$.each(myJson.allconfig, function (key, value) {
var rowArray = [];
rowArray.push(key);
$.each(myJson.allconfig[key], function (key1, value1) {
rowArray.push(value1);
});
newJson.push(rowArray);
});
$('#json-table-edit').dataTable({
"bJQueryUI": true,
"bStateSave": true,
"sPaginationType": "full_numbers",
"bProcessing": true,
"oLanguage": {
"sLengthMenu": ' <select>' + '<option value="10" selected="selected">Filter</option>' + '<option value="10">10</option>' + '<option value="20">20</option>' + '<option value="30">30</option>' + '<option value="40">40</option>' + '<option value="50">50</option>' + '<option value="-1">All</option>' + '</select>'
},
"aaData": newJson
});

This is possible using the split() method. split(",") will give you an array of separate strings for each coma separated entity. You can then use the jQuery .each() method to iterate over the array and append each string to the DOM wrapped in <option> tags.
something like this:
var data = {
"allconfig": {
"card.inserted": {
"value": "Inserted, Not Inserted",
},
"card.cisproc": {
"value": "Processed",
}
}
}
var options = (data.allconfig["card.inserted"]["value"]).split(",");
$("body").append("<select id='select'></select>");
//I am appending this to the body, but you can change body to
// whatever element/class/id you want
$(options).each(function() {
$("#select").append("<option>"+this+"</option>");
});
//I have also given the select an id so this code can be used on pages that have multiple select elements
here is a fiddle

One way would be to use the plain Javascript method .split().
You'll need to split the value string, which will then turn the comma-seperated string into an array. Then you'll need to run over the array to make your select dropdown.
Something like this inside of your JSON return function (not exactly these variable names, just an example to show you the idea):
$('#SelectContainer').html('<select name="mySelect">');
var options = value.split(',');
for (counter=0; counter < options.length; counter++)
{
$('#SelectContainer').append('<option value="' + options[counter] + '">' + options[counter] + '</option>');
}
$('#SelectContainer').append('</select>');

Related

Creating a button with each input JSON object using JavaScript

I got a situation where I would like to read some data off a JSON format, however I am having some issues understanding how I should construct the button dynamically from JSON object.
My scenario is as follows:
$(document).ready(function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
// listen for mqtt_message events
// when a new message is received, log and append the data to the page
socket.on('mqtt_message', function(data) {
var json = JSON.parse(data['payload']);
var table = $("<table>");
table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
for (var i = 0; i < json.length; i++) {
var row = $("<tr><td>" + json[i]["name"] + json[i]["ID"] + "</td></tr>");
table.append(row);
}
table.appendTo($("#container"));
})
});
where
json = {"host":abc,"name":123,"id":345}
I have to make hostname as button and when I click on that button for example here, name "abc", i will get details name and id in table format. I have created table but it is showing whole table not that scenario which I actually want.
I am new to the JavaScript, facing issues here.
1) The JSON data doesn't seem to be an array, you can't loop through it.
2) You have to append the header to a <thead> element.
3) You have to append the table row to a <tbody> element.
All tables should have a <thead> and a <tbody> element, so just add it to your HTML code.
<div id="container">
<table style="display:none">
<thead>
<tr>
<th>Host</th>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Then you append your data to these HTML elements, like so. If your data is an object and not an array, just don't loop through it but instead call the properties as is.
var json = [{
host: "Some host IP",
name: "Some name",
id: 345
},
{
host: "Some other host IP",
name: "Some other name",
id: 987
}
];
var $container = $("#container");
var $thead = $("#container table thead");
var $tbody = $("#container table tbody");
var $row = $("#container table tbody tr");
// Loop through items in JSON data..
json.forEach(function(item) {
var $button = $("<button>" + item.host + "</button>");
$container.prepend($button);
// Button click handler..
$button.on("click", function() {
// Replace row HTML..
$row.html('<td>' + item.host + '</td>' + '<td>' + item.name + '</td>' + '<td>' + item.id + '</td>');
// Show table if it's not already visible..
$("#container table").show();
});
});
Full code here:
https://jsfiddle.net/amsv/15h74uy6/
Vanilla JS, ie. without jQuery:
https://jsfiddle.net/amsv/15h74uy6/72/
let json = [
{"host":abc,"name":123,"id":345},
{"host":def,"name":456,"id":345}
]
In your html write
<button *ngFor = 'let item of json' (click)='buttonOnClick($event)'>
{{item.host}}
</button>
Above code will render two buttons for each element in the array
In your ts write
buttonOnClick(event) {
console.log(event) // you will get the corresponding object from the array
}
var sampleData = [{ "host": "abc", "name": 123, "id": 345 }, { "host": "xyz", "name": 456, "id": 678 }]
When data is received you should create button which shows table and set data attribute of button with received data.
for (var i = 0; i < sampleData.length; i++) {
var item = sampleData[i];
var button = $('<button />');
button.text(item.host);
button.data('data', JSON.stringify(item))
button.on('click', function (e) {
e.preventDefault();
showTable(e);
});
$('#buttons').append(button);
}
showTable is like as below
function showTable(e) {
var json = JSON.parse($(e.target).data('data'));
var table = $("<table>");
table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
var row = $("<tr><td>" + json["host"] + "</td><td>" + json["name"] + "</td><td>" + json["id"] + "</td></tr>");
table.append(row);
$("#table").html(table);
}
Html is below:
<div id="container">
<div id="buttons">
</div>
<div id="table">
</div>
</div>

Get selected drop-down value of a row in html table using JavaScript/jQuery

I have a html table with 4 columns and multiple rows
column1 : simple text
column2 : simple text
column3 : select list with 2 values
column4 : Button that performs some operation
At run time, I want to get the selected / entered values for all the columns of that row against which column4 button is clicked. I know a little of JavaScript/jQuery.
Here is the static table code
<table id="invoiceTbl" border="1">
<thead>
<tr>
<th>Broker info</th>
<th>Receivable Amount</th>
<<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
And I am populating table i.e. inserting data on AJAX call like this:
$.ajax({
type: "POST",
data: $('#searchDetails').serialize(),
async: false,
cache: false,
url: "/opsadmin/search.json",
dataType: 'json',
success: function (result) {
var i = 1;
$.each(result, function (index, value) {
alert(index + ": " + value.brokerInfo);
$('table#invoiceTbl TBODY').append('<tr> <td>' + i + '</td><td>' + value.brokerInfo + '</td><td>' + value.receivableAmount + '</td><td><select name="act" id="s"><option>PENDING</option><option>CLEARED</option></select></td><td><input type="button" value="Process" onclick="updateStatus(\'' + index + '\')"</input></td></tr>');
i++;
});
}
});
return false;
First set the unique ID to each of your "select" with help of index like:
'<select name="act" id="s'+ index +'">'
and pass the index with "updateStatus(index)" function call.
function updateStatus(index) {
$('#s'+index).val(); // value of selected box.
}
$("#invoiceTbl input[type=button]").click(function(e){
$(e.target).closest("tr").find("td").slice(0,2).each(function(){
console.log($(this).text());
});
});
On #button click you will get an array (arr) that holds the values of the clicked row cells:
$('#button').on('click', function() {
var arr = [];
$(this).closest('tr').find('td').each(function() {
var that = $(this);
if (that.find('input[type="text"]').length > 0) {
arr.push(that.find('input[type="text"]').val());
} else if (that.find('select').length > 0) {
arr.push(that.find('select').val());
} else {
arr.push(that.text());
}
});
alert(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>text</td>
<td>text2</td>
<td>
<select>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
</select>
</td>
<td><button id="button">Click</button></td>
</tr>
</tbody>
</table>
There's already a few good answers, but my solution is a bit different:
$("#invoiceTbl tr").each(function(){
var select = $(this).find("select");
var button = $(this).find("button");
button.click(function(){
alert(select.val());
});
});
If you also want the content of the other columns, that's a bit more difficult:
$("#invoiceTbl tr").each(function(){
var tr = $(this);
var button = $(this).find("button");
button.click(function(){
tr.find("td").each(function(){
var select = $(this).find("select");
var td_button = $(this).find("button");
if(!td_button.length)
{
if(select.length)
console.log(select.val());
else
console.log($(this).text());
}
});
});
});
Check out https://jsfiddle.net/cgfjewoe/ to see it run.

Get the Checked and Unchecked table data via jquery

I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});

How do I create HTML table using jQuery dynamically?

I am trying to create a HTML table like the following dynamically using jQuery:
<table id='providersFormElementsTable'>
<tr>
<td>Nickname</td>
<td><input type="text" id="nickname" name="nickname"></td>
</tr>
<tr>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>
</tr>
</table>
This is my actual table :
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
This is the method which will create tr and td elements taking id and labelText:
function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
});
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);
// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}
I also have a value which will be shown as tool tip.
Please help me to create a table dynamically with tool tip and tr td.
EDIT:
I have almost done with the following code:
function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip
});
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
Here label is coming properly and the input box is not coming and it shows [object Object] where the text box has to come...
When I printed the textInputBox using console.log, I get the following:
[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
What could be the issue?
Thanks to #theghostofc who showed me path... :)
You may use two options:
createElement
InnerHTML
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Edit:
Check Dynamic creation of table with DOM
Edit 2:
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
WORKING DEMO:
Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.
It's much easier to construct just the html and change the id s of the label and input according to your needs.
FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.
var obj = JSON.parse(msg);
var tableString ="<table id='tbla'>";
tableString +="<th><td>Name<td>City<td>Birthday</th>";
for (var i=0; i<obj.length; i++){
//alert(obj[i].name);
tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
}
tableString +="</table>";
alert(tableString);
$('#divb').html(tableString);
HERE IS THE CODE FOR gg_stringformat
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}

How to include array content in HTML?

I have this code
var users = result.users; // array
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
},
buttons: {
"Okay": function() {
$(this).dialog("close");
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
}
}
});
where the array contain data in the form of
{"ss":"Sandra Schlichting","fn":"Full name"}
What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)
<table>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
<tr> <td>ss </td> <td>Sandra Schlichting</td> </tr>
<tr> <td>fn </td> <td>Full name </td> </tr>
</table>
and have that replaced with <b>New text goes here</b> in
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
From what I can tell $.each() should be used for this.
But still I can't quite figure out how to get started.
Can anyone help me out?
You can use a JS for-in to loop through it.
<table id='nameTable'>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
</table>
var names = {
"ss": "Sandra Schlichting",
"fn": "Full name"
};
var $table = $('#nameTable');
var row = '';
for (name in names) {
row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)
Here's a fiddle : http://jsfiddle.net/exP2b/4/
function makeTable(users) {
var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));
Working here
$.each documentation

Categories

Resources