scoping html data with js or jquery - javascript

This is my html ( in twig template )
<li id="{{folder.id}}" data-jstree='{"icon":"glyphicon glyphicon-tags", "type":"folder"}' >{{folder.name}}
I am trying to get the value of 'type' from 'data-jstree'.
I tried using
var node_id = ref.get_node(sel[i]).id;
var type = $("#"+node_id).attr("data-jstree");
but that gives me this : {"icon":"glyphicon glyphicon-tag", "type":"tag"}
and i only need the value of type.
Thanks in advance.

var type = JSON.parse($("#"+node_id).attr("data-jstree")).type

you need to parse the string into json. do something like this:
var node_id = ref.get_node(sel[i]).id;
var type = $("#"+node_id).attr("data-jstree");
type = JSON.parse(type).type;

Related

Get specific field from property

I am new to JavaScript and Dynamics CRM.
I have following code:
var analysisCode = Xrm.Page.getAttribute("rf_analysiscode").getValue()[0].entityValues;
As value for analysisCode, I get following output:
{
"rf_name":{"name":"rf_name","value":"ABC"},
"rf_code":{"name":"rf_code","value":"ABC"},
"createdon":{"name":"createdon","value":"24.1.2022 10.39"}
}
But I want to get just the rf_code. How do I retrieve that?
Parse your result to JSON like this:
const analysisCodeObj = JSON.parse(analysisCode);
Get rf_code like this:
const rfCodeObj = analysisCodeObj["rf_code"];
Try this:
analysisCode = {
"rf_name":{"name":"rf_name","value":"ABC"},
"rf_code":{"name":"rf_code","value":"ABC"},
"createdon":{"name":"createdon","value":"24.1.2022 10.39"}
};
let rf_code = analysisCode.rf_code;
console.log('rf_code : ', rf_code);
console.log('rf_code Value : ', rf_code.value);
If you are getting your output in String, Firstly need to parse output and then you can get any value from that json.
Try this:
analysisCode = '{"rf_name":{"name":"rf_name","value":"ABC"},"rf_code":{"name":"rf_code","value":"ABC"},"createdon":{"name":"createdon","value":"24.1.2022 10.39"}}'
let rf_code = JSON.parse(analysisCode).rf_code;
console.log('rf_code : ', rf_code);
console.log('rf_code Value : ', rf_code.value);

How to iterate a C# generic list in javascript? [duplicate]

In viewmodel object, below is the property:
public IList<CollegeInformationDTO> CollegeInformationlist { get; set; }
In VIEW, javascript is as follow:
var obj = JSON.stringify('#Model.CollegeInformationlist');
alert(obj[1].State); //NOT WORKING, giving string char
$.each('#Model.CollegeInformationlist', function (i, item) {
var obj = JSON.stringify(item);
var r = $.parseJSON(obj);
alert(r.State); //just giving undefined.
});
Please guide here, how i can get JSON object in javascript.
You could use the following:
var json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
This would output the following (without seeing your model I've only included one field):
<script>
var json = [{"State":"a state"}];
</script>
Working Fiddle
AspNetCore
AspNetCore uses Json.Serialize intead of Json.Encode
var json = #Html.Raw(Json.Serialize(#Model.CollegeInformationlist));
MVC 5/6
You can use Newtonsoft for this:
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model,
Newtonsoft.Json.Formatting.Indented))
This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().
It should be as simple as:
<script>
var json = #Json.Serialize(Model.CollegeInformationlist);
</script>
After use codevar json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json));
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
#model IEnumerable<CollegeInformationDTO>
#section Scripts{
<script>
var jsArray = JSON.parse('#Html.Raw(Json.Encode(#Model))');
</script>
}
If You want make json object from yor model do like this :
foreach (var item in Persons)
{
var jsonObj=["FirstName":"#item.FirstName"]
}
Or Use Json.Net to make json from your model :
string json = JsonConvert.SerializeObject(person);
The following code worked for me
var chartD = JSON.parse(JSON.stringify([#Json.Serialize(#Model)]));

How to access value of variable in Mongo?

var a = "act";
db.s.findOne( {
BrandId: doc.BrandId,
a : {$exists:false}
} ).a;
I try to pass the value of variable "a" to my MongoScript. But it looks it can not be simply used. anyone can help?
Build your query step by step and do not use . use [] instead
var a = 'act';
var query = {BrandId: doc.BrandId};
query[a] = {$exists:false};
db.s.findOne(query)[a];
Note:
query.act == query['act'].
Just some javascript tricks.

Read Json Variable

{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}
How do i write the code to read the teamid and teamname so as to store them in seperate variables?
Please Help!
If it is a JSON string, parse it...
var obj = jQuery.parseJSON(jsonString);
Then work with the information
obj.TeamList[0].teamid;
obj.TeamList[0].teamname;
TeamList is an array so if you have more than one "team" you'll need to loop over them.
You have an object containing an array TeamList, which has one object as its elements:
var tl = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};
var id = tl.TeamList[0].teamid;
var name = tl.TeamList[0].teamname;
If the example you have posted in contained as a string you can parse it like so with javascript...
var jsonObject = JSON.parse(myJsonString);
you can then access your array like so...
jsonObject.TeamList
and each item in TeamList...
jsonObject.TeamList[i].teamid
jsonObject.TeamList[i].teamname
finally assuming you have one item in TeamList and making an attemp to directly answers you question...
var teamid = jsonObject.TeamList[0].teamid;
var teamname = jsonObject.TeamList[0].teamname;
hope that makes sense
in which language? Basically after parsing using json you would do something like this on the result:
result["TeamList"][0]["teamname"] to get teamname and result["TeamList"][0]["teamid"] to get teamid.
If you can use json_decode, like this :
$content = '{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}';
$json = json_decode($content);
$obj = $json->{'TeamList'}[0];
print $obj->{'teamid'}."//".$obj->{'teamname'};
You had tagged your question as jQuery? We're you wanting to display this information on a page?
Given some sample html:
<label>Team ID:</label>
<div id="teamid"></div>
<label>Team Name:</label>
<div id="teamname"></div>
And a little jquery:
var obj = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};
$('#teamid').html(obj.TeamList[0].teamid);
$('#teamname').html(obj.TeamList[0].teamname);
Would allow you to accomplish this. As others have pointed out you would need to iterate over the collection if there were multiple teams.

Is it possible to append value in an existing object - jquery

Consider i am having an object "req".
When i use console.log(req) i get
Object { term="s"}
My requirement is to append an value with the existing object.
My expected requirement is to be like this:
Object { term="s", st_id = "512"}
Is it possible to do the above?
If yes, how ?
Thanks in advance..
There are several ways to do it;
Plain javascript:
var req = { "term" : "s" };
req.st_id = "512";
Because javascript objects behaves like associative arrays* you can also use this:
var req = { "term" : "s" };
req["st_id"] = "512";
jQuery way $.extend():
var req = { "term" : "s" };
$.extend(req, { "st_id" : "512" });
You can do this in a couple of ways:
req.st_id = "512";
or
req["st_id"] = "512";
The second of these is especially useful if the variable name is dynamic, e.g. a variable could be used instead of the string literal:
var key = "st_id";
req[key] = "512";
Yes this is possible, to add properties to a value simply use the following syntax:
req.st_id = "512";

Categories