How can I access array element value in json - javascript

I'm not able to access _sValues in my html page, however i can able to console.log the interested _sValues array element in console.
JSON
[
{
"_this":{
"_isEvent":false,
"_sNames":[
"name",
"tag",
"notes",
"input",
"type",
"action"
],
"_sValues":[
"Testing01",
"#13",
"1504013826",
"No details",
"cType",
"NA"
],
"_cName":"namesList",
"_dName":"TEST",
"_id":"12345",
}
}
]
HTML
<th class="col-md-5 col-xs-5" data-field="_this._sValues[1]" data-sortable="true">S-VALUES</th>
I would like to see #13 displayed on the page instead i don't see any values or console error. However i can display all values by doing _this.sValues
SCRIPT
var data;
$(function () {
$.getJSON("http://localhost:8080/services/webapi/getAllData", function(json){
data = json;
$('#table').bootstrapTable({
data: data
});
});
});
DEV TOOL
data[0]._this._sValues[1]
"#13"

In your case,
i assume you only have one row.
$(".col-md-5").attr("data-field",data[0]._this._sValues[1]);
It will inject the data to html.
If you have multi row, you can use for loop.

I believe you have a silent error. It has to do with the trailing comma in your data object.
"_id":"12345",
// should be
"_id":"12345"
That's all I noticed. I Courbet wrong but I know trailing commas mess with some browsers.

Related

Formatting server side jQuery Datatable

I am trying to format the front end look of my jQuery DataTable
I currently have it looking like this https://imgur.com/a/PPgL48Y
I need the repeating items in each row to be remove for example in the first row there are 2 Owner 1's. I only want to display a single Owner 1 in that row.
The other issue is in row 2, Url1 is followed by a comma then Url 2 but i want
Url1
Url2
In the row, so removing the comma and adding a new line in that col
My data is being collected via server side processing
My current jQuery code
<script type="text/javascript" >
$('#result').DataTable({
"serverSide":true,
"filter": false,
"orderMulti": false,
"ajax": "DetailedSearch?handler=ServerSideDataTable",
"columns":[
{"data": "location",
"render": function(data,type,row){
return row.location;
}
},
{"data": "contactAndRole",
"render": function(data,type,row){
return data.key + " - " + data.value;
}},
{"data": "server", "sortable": "false"},
{"data": "urls",
"render": function(data,type,row){
return row.urls + '<br>';
}
}
],
rowGroup:{
dataSrc:'appName'
}
});
</script>
Can i add some html elements? like a br after each url, or can the table be constructed with pure html then passed onto data tables to output?
I've looked into the HTML templates, and standalone documentation on the data tables website but nothing seems to be helpful.
The commas for the url's array are because of the default way arrays are processed to strings to be printed into the html in the dom
You could join() them yourself using a <br> separator instead
return row.urls.join('<br/>')

PolymerJS POST JSON formatting

I am trying to POST using PolymerJS ajax-forms and I encounter a weird JSON format error. Can someone tell me why the quotes are missing around the keys? The only workaround I can think of is manually constructing the body with the quotes around the keys.
Code Snippet :
How I receive the values (rest are the same with the ids changed):
<div>
<paper-input label="Title" id="course-title" floatingLabel value="{{item.title}}"></paper-input>
</div>
<access-core-ajax
auto = "false"
url="domain/courses"
response="{{response}}"
method="post"
id="postCourse"
contentType="application/json"
headers='{"Accept": "application/json", "Content-Type":"application/json"}',
body = "{{item}}">
<template id="get-response-template" repeat="{{item in response.entries}}">
<p>Errors</p>
</template>
</access-core-ajax>
Polymer('create-new-course-page',{
domReady: function() {
console.log("Log: create-new-courses-page - Looks like we are domReady");
},
created: function() {
console.log("Item initialized");
this.item = {};
this.data={};
},
createNewCourse: function(event) {
console.log("HERE IS BODY", this.item);
this.$.postCourse.go();
}
And the JSON is see on the log:
{
title: "WRU",
// rest of key & values, where the keys are without the ""
}
You need to turn the body into a JSON string first. JSON.stringify can help.
...
createNewCourse: function(e) {
this.$.postCourse.body = JSON.stringify(this.item);
this.$.postCourse.go();
}
You may need to remove the body attribute here. You can also remove that auto attribute since by default it is false.

How to use function in Kendo Grid Column Template with AngularJS

I have a column in a Kendo grid that I want to perform some specific logic for when rendering, and am using Angular. I have the grid columns set up using the k-columns directive.
After looking at the documentation, it seemed simple: I could add the template option to my column, define the function to perform my logic, and pass the dataItem value in. What I have looks something like this:
k-columns='[{ field: "Name", title: "Name",
template: function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}
}]'
However, running this causes a syntax error complaining about the character '{' that forms the opening of the block in my function.
I have seen several examples of defining a template function in this format. Is there something else that needs to be done for this to work? Am I doing something incorrectly? Is there another way of defining the template as a function and passing the column data to it? (I tried making a function on my $scope, which worked, except I couldn't figure out how to get data passed into the function.)
Thank you for your help.
It appears that defining a column template in this fashion isn't supported when using AngularJS and Kendo. This approach works for projects that do not use Angular (standard MVVM), but fails with its inclusion.
The workaround that a colleague of mine discovered is to build the template using ng-bind to specify a templating function on the $scope, all inside of a span:
template: "<span ng-bind=templateFunction(dataItem.Name)>#: data.Name# </span>"
This is the default column templating approach that is implemented by Telerik in their Kendo-Angular source code. I don't know yet if the data.Name value is required or not, but this works for us.
Warning: Don't have access to Kendo to test the code at the moment, but this should be very close
In your case, you are assigning a a string to the value of k-columns and that string contains the the word function and your curly brace {
You need to make sure the function gets executed ... something like this:
k-columns=[
{
field: "Name",
title: "Name",
template: (function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}())
}
];
Note the difference:
We create an object -- a real honest-to-goodness object, and we use an IIFE to populate the template property.
Maybe, it will be useful for someone - this code works for me too:
columns: [
{
field: "processed",
title:"Processed",
width: "100px",
template: '<input type="checkbox" ng-model="dataItem.processed" />'
},
and you get the two-way binding with something like this:
<div class="col-md-2">
<label class="checkbox-inline">
<input type="checkbox" ng-model="vm.selectedInvoice.processed">
processed
</label>
</div>
This can be done via the columns.template parameter by supplying a callback function whose parameter is an object representing the row. If you give the row a field named name, this will be the property of the object you reference:
$("#grid").kendoGrid({
columns: [ {
field: "name",
title: "Name",
template: function(data) {
return data.name + "has my respect."
}
}],
dataSource: [ { name: "Jane Doe" }, { name: "John Doe" } ]
});
More information is available on Kendo's columns.template reference page.
After hours of searching. Here is the conclusion that worked:
access your grid data as {{dataItem.masterNoteId}} and your $scope data as simply the property name or function.
Example
template: '<i class="fa fa-edit"></i>',
I really hope this safes somebody life :)
just use like my example:
}, {
field: "TrackingNumber",
title: "#T("Admin.Orders.Shipments.TrackingNumber")",
//template: '<a class="k-link" href="#Url.Content("~/Admin/Shipment/ShipmentDetails/")#=Id#">#=kendo.htmlEncode(TrackingNumber)#</a>'
}, {
field: "ShippingMethodName",
title: "#T("Admin.Orders.Shipments.ShippingMethodName")",
template:function(dataItem) {
var template;
var ShippingMethodPluginName = dataItem.ShippingMethodPluginName;
var IsReferanceActive = dataItem.IsReferanceActive;
var ShippingMethodName = dataItem.ShippingMethodName;
var CargoReferanceNo = dataItem.CargoReferanceNo;
var ShipmentStatusId = dataItem.ShipmentStatusId;
if (ShipmentStatusId == 7) {
return "<div align='center'><label class='label-control'><b style='color:red'>Sipariş İptal Edildi<b></label></div>";
} else {
if (ShippingMethodPluginName == "Shipping.ArasCargo" || ShippingMethodPluginName == "Shipping.ArasCargoMP") {
template =
"<div align='center'><img src = '/content/images/aras-kargo-logo.png' width = '80' height = '40'/> <label class='label-control'><b>Delopi Aras Kargo Kodu<b></label>";
if (IsReferanceActive) {
template =
template +
"<label class='label-control'><b style='color:red; font-size:20px'>"+CargoReferanceNo+"<b></label></div>";
}
return template;
}

Dojo: dijit.form.filteringselect dynamically add options from Json

I am getting data from json file, now i want to add it to filteringselect. i tried below code but its not adding, please help me
HTML code==
<select data-dojo-type="dijit/form/FilteringSelect"
id="education"></select>
Javascrip code==
request.get("/json/education.json", {
handleAs: "json"
}).then(function(data) {
var node = dijit.byId('education');
dojo.forEach(data.items, function(desc, index){
node.addOption({
label: desc.name,
value: desc.value
});
});
},
function(error){});
Json code
{
"title":"Education",
"items":[
{"name":"Select Education","value":"0"},
{"name":"B.A", "value":"1"},
{"name":"B.Sc" ,"value":"2"},
...........................
The store of FilteringSelect can be set dynamically, based on the ajax call.
var str = new dojo.store.Memory(optionData);
dijit.byId('widgetId').set('store',str);
But, your json data must be like this:-
var optionData={
data:[
{id:'aaaaaa',name:'aaaaaa'},
{id:'bbbbbb',name:'bbbbbb'}
]
};
The above example will actually replace the store. If, the new data from ajax call need to be appended to the existing options, then
//str is the existing store of FilteringSelect field above
dojo.forEach(result.data, function(optionSet, index){
str.add(optionSet);
});
Note to remember: 'addOption' is available only for Select. Not for FilteringSelect.
I hope this helps:
dijit.byId("select_id").store.root.add(dojo.create("option",{ value: "some", innerHTML: "label of option"}));
To remove the existing elements did just that:
var size = dijit.byId("select_id").store.root.removeChild.length;
for(var i=size; i>=0; i--){ dijit.byId("select_id").store.root.removeChild(dijit.byId("select_id").store.root.children[size-1]);
}

Javascript Error,Escaping Problem,Grid not working,Error on Firebug

we are just started with Sigma Grid ,and it is awesome in its functionality when we compared to other Grids.
But i encountered some problem with Sigma Grid ,or may be with javascript.
I dont know whether the problem is with Grid or with my code.
I have a table with 3 fields namely MailID,MailName,MailData.
MailID is int ,MailName and MailData contains HTML content and it save as string in database.
When i load the Grid,i have some problems.
Problem 1 :
As i said above the Maildata contain html content,the following image is just a example with <*b> ,u can see that the HTML is automatically rendering on the grid itself ,i need the exact string.
please check the following image.
Problem 2 :
as u can see i have links on the grid,for edit,send,delete but on one filed its damaged.[check the image below ]
the code i used to render links is following .
{id: 'mailid' , header: "Action", width :120 , resizable : false, sortable : false , printable : false ,
renderer : function(value ,record,columnObj,grid,colNo,rowNo){
var no= record[columnObj.fieldIndex];
var cod = (record['maildata']);
return 'Edit | Delete';
Problem 3 :
The third value of MailData is 5 and it is integer ,when i alert the value its shows it correctly.
check the following image.
But when i alert the second value of maildata it giving error ,the second value of MailData is "hai newuser" ,it showing the following error on firebug.
missing ) after argument list
alert(hai newuser)
check the image below.
But when i alert 9th value of MailData it run correctly ,the content is <b>poy</b> ,this one is also save as string,but the grid automatically BOLD [which i dnt like].Check the image below.
also there are some others the 7the value contain ;".: etc ,also /b ,when i alert the data it showing the following error,
unexpected end of XML source
alert(<b>jjfdslkdjflsdnfsldfnf
dsOptions and ColOptions are following .
var dsOption= {
fields :[
{name : 'mailid' },
{name : 'mailname',type:"text" },
{name : 'maildata',type:"text" }
],
recordType : 'object',
}
function my_renderer(value ,record,columnObj,grid,colNo,rowNo)
{
var no= record[columnObj.fieldIndex];
return "<img src=\"./images/flag_" + no.toLowerCase() + ".gif\">";
}
function showalert(no)
{
$(document).ready(function()
{
$.post("http://localhost/power/index.php/power/give",{ name: no}, function(data)
{
//alert("Data Loaded: " + data);
$("#editor").show("fast");
$( '#txtar' ).ckeditor();
$('#txtar' ).val( data.maildata );
//$("#editor").html(data);
},"json"
);
});
}
var colsOption = [
{id: 'mailid' , header: "Mail ID" , width :60},
{id: 'mailname' , header: "Mail Name" , width :160 ,type:"text"},
{id: 'maildata' , header: "Mail Data" , width :190,type:"text" },
{header: "Group" , width :70,
editor : { type :"select" ,options : {'php':'php','asp':'asp'}
,defaultText : 'php' } },
{id: 'mailid' , header: "Action", width :120 , resizable : false, sortable : false , printable : false ,
renderer : function(value ,record,columnObj,grid,colNo,rowNo){
var no= record[columnObj.fieldIndex];
var cod = (record['maildata']);
return 'Edit | Delete';
} }
];
I am littlebit new in Javascript and Sigmagrid,i think that i am doing something worst with codes,pls help me to success.
Thank you.
Note : i posted the same Question on Sigma Grid Forum too,i think that it is not a problem.
Problem 2
The string cod contains a >
Problem 3
The string hai newuser needs to be contained in " or ' or it is considered a variable name
Basically you have to decide -- are you going to validate the html or not. If you don't validate the HTML then html errors in the data will show as errors on your page. You could also HTML escape the html so you will see the HTML codes -- this is probably the best plan.
Other sites use (like this one) use markdown -- this is easier to validate -- then they generate the actual HTML before display.
In addition you are having problems with the alert. Alert displays strings not HTML so you will see what you are seeing -- different results than expected depending on the HTML.
I would take a step back and ask yourself -- what is the type of the data, how am I going to display it. How am I going to validate that if it is HTML it is valid.
There are the problems you need to address -- your examples all stem from this problem.

Categories

Resources