How to assign variable to json object - javascript

'I'm trying to assign a variable from a parent div to the json string of a child table and can't seem to get my javascript straight.
What I'd like to see, or some variation of:
{"blocks":[{"id":"115",courses:[{"Semester":"S,F","Credits":"3","Subject":"ACT"}‌​, {"Semester":"F","Credits":"6","Subject":"CSI"}]}]
And the jQuery I have so far.
$('#update').click(function (e){
var table = $('#table').tableToJSON();
var blockId = $('#table').closest('div.Block').attr('id');
table = {"block":table};
document.getElementById('courseList').value = JSON.stringify(table);
}
I'm not sure how to add in the variable that I need in the object? How would I insert blockId?

I'm assuming bracket notation is what you're really looking for :
$('#update').on('click', function(){
var table = $('#table').tableToJSON();
var blockId = $('#table').closest('div.Block').attr('id');
var table2 = {};
table2[blockId] = table;
$('#courseList').val( JSON.stringify(table2) );
});

Related

inserting text-field to table cell using javascript

I am making a program in which I want to add an input field to a table cell.
Look at the code below:
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
newf.appendChild(newl);
}
newf gets the value of td_song,td_artist etc and these are already defined as:
var td_song = document.createElement("td");
var td_artist = document.createElement("td");
var td_genre = document.createElement("td");
in the same function and then I've appended them to a table and it works fine
but when I am creating the input element then there's an error:
Uncaught TypeError: newf.appendChild is not a function
I know it has no end tag and it needs to be in a form element, but the error is same when I try to add any other element.
Help!
the value stored in newf is a string, not a DOM element; appendChild is not a valid method on strings. Just because the string value stored in newf matches the name of a variable you created (td_song, etc), does not mean it is now a handle to that element. You would be better of storing your created elements in an object, keyed off of that value:
var elems = {
td_song: document.createElement("td"),
td_artist: document.createElement("td"),
td_genre: document.createElement("td")
};
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
elems[newf].appendChild(newl);
}
After this line, the contents of newf is simply a string reading "td_song" for example.
var newf = "td_" + arr_title[title];
You are probably getting a JS error of "newf is not a function" ?
If you want newf to really be the one of those vars, you could explore using eval()
var newf = eval("td_" + arr_title[title]);
Does the <td> you're trying to append to have an ID of "td_" + arr_title[title]?
If so, you need to do...
var newf = document.getElementById("td_" + arr_title[title]);
newf.appendChild(newl);
newf is a string and you can't append child to string, if you want to refer to the variable with this name you should use window :
window[newf].appendChild(newl);
Hope this helps.

Changing the selected object in Javascript

What I am trying to do is rewrite content on the page depending on which object I have selected. I have some objects like so:
function floorPlan(name,rev,sqft,bedrm,bthrm) {
this.name = name;
this.rev = rev;
this.sqft = sqft;
this.bedrm = bedrm;
this.bthrm = bthrm;
}
// 1BR Plans
var a1 = new floorPlan('A1',false,557,1,1);
var a2 = new floorPlan('A2',false,652,1,1);
var a3 = new floorPlan('A3',false,654,1,1);
var a4 = new floorPlan('A4',false,705,1,1);
var a5 = new floorPlan('A5',false,788,1,1);
// The Selected plan
var currentPlan = floorPlan.a1;
I am having the user control this via a .click() function in a menu:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = floorPlan.current;
});
The problem is that currentPlan keeps coming back as undefined and I have no idea why. Should I be defining currentPlan differently? I can't seem to find any resources to help me find the answer.
UPDATED:
I switched out a few parts per your suggestions:
// The Selected plan
var currentPlan = a1;
and....
// Define the currentPlan
var current = $(this).attr('id');
currentPlan = current;
However, everything is still returning undefined in the click function (not initially though).
First of all $('this') should be $(this)
Secondly you're trying to use a read ID from your LI as a variable name. That doesn't work. If you store your plans in an array you can use the ID to search in that array:
var plans=Array();
plans["a1"]=new floorPlan('A1',false,557,1,1);
plans["a2"]=new floorPlan('A2',false,652,1,1);
Then your jQuery code should be altered to this:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = plans[current];
alert(currentPlan);
});
I created a JSFiddle for this. Is this what you were looking for?
Use as floorPlan.currentPlan = a1;
instead of var currentPlan = floorPlan.a1;
Please create a plunker and will correct if any issue.
I spot two errors.
When you write var inside a function, that variable is only accessible with that function. Right now you are creating a new variable in your anonymous function that is "hiding" the global variable with the same name.
So, first remove the var keyword from the assignment in the anonymous function (the one you call on "click").
Secondly I think you mean to assign floorPlan[current].
The final line should read:
currentPlan = floorPlan[current];

How to get the displayed data of KendoGrid in json format?

I have a kendoGrid and i would like to get the JSON out of it after filtering and sorting how do I achieve this?
something like the following,
var grid = $("#grid").data("kendoGrid");
alert(grid.dataSource.data.json); // I could dig through grid.dataSource.data and I see a function ( .json doen't exist I put it there so you know what i want to achieve )
Thanks any help is greatly appreciated!
I think you're looking for
var displayedData = $("#YourGrid").data().kendoGrid.dataSource.view()
Then stringify it as follows:
var displayedDataAsJSON = JSON.stringify(displayedData);
Hope this helps!
If you want to get all pages of the filtered data you can use this:
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filters = dataSource.filter();
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
Make sure to check if filters exist before trying to apply them or Kendo will complain.
To get count of all rows in grid
$('#YourGridName').data("kendoGrid").dataSource.total()
To get specific row items
$('#YourGridName').data("kendoGrid").dataSource.data()[1]
To get all rows in grid
$('#YourGridName').data("kendoGrid").dataSource.data()
Json to all rows in grid
JSON.stringify($('#YourGridName').data("kendoGrid").dataSource.data())
For the JSON part, there's a helper function to extract the data in JSON format that can help:
var displayedData = $("#YourGrid").data().kendoGrid.dataSource.view().toJSON()
EDIT: after some errors with the above method due to kendo grid behavior, I found this article that solves the problem:
Kendo DataSource view not always return observablearray
Something like this, to display only data that is being viewed at the moment. Also extended the grid to provide these functions all over the app.
/**
* Extends kendo grid to return current displayed data
* on a 2-dimensional array
*/
var KendoGrid = window.kendo.ui.Grid;
KendoGrid.fn.getDisplayedData = function(){
var items = this.items();
var displayedData = new Array();
$.each(items,function(key, value) {
var dataItem = new Array();
$(value).find('td').each (function() {
var td = $(this);
if(!td.is(':visible')){
//element isn't visible, don't show
return;//continues to next element, that is next td
}
if(td.children().length == 0){
//if no children get text
dataItem.push(td.text());
} else{
//if children, find leaf child, where its text is the td content
var leafElement = innerMost($(this));
dataItem.push(leafElement.text());
}
});
displayedData.push(dataItem);
});
return displayedData;
};
KendoGrid.fn.getDisplayedColumns = function(){
var grid = this.element;
var displayedColumns = new Array();
$(grid).find('th').each(function(){
var th = $(this);
if(!th.is(':visible')){
//element isn't visible, don't show
return;//continues to next element, that is next th
}
//column is either k-link or plain text like <th>Column</th>
//so we extract text using this if:
var kLink = th.find(".k-link")[0];
if(kLink){
displayedColumns.push(kLink.text);
} else{
displayedColumns.push(th.text());
}
});
return displayedColumns;
};
/**
* Finds the leaf node of an HTML structure
*/
function innerMost( root ) {
var $children = $( root ).children();
while ( true ) {
var $temp = $children.children();
if($temp.length > 0) $children = $temp;
else return $children;
}
}

How to wrap dynamically selected ids using jquery or javascript

I am working on a project in Google Blogger. First i want to explain a thing.
In blogger every post that is created has a unique id assigned to it by blogger itself. This id can be retrieved using Blogger JSON. So i have retrieved the ids of four recent posts using JSON.
I want to wrap these first four id containers around a DIV container using JQuery or Javascript.
The problem is when i use these ids absolutely in the selector $ and use the wrapAll() function the id container's gets wrapped up. But as i said i'm using JSON to get the container id's so the values of ID's are stored in variable's and when i use those variable as selection for wrapAll() function it doesn't work.
I have demos of both those situation's which can be seen by going to this blog http://youblog-demo.blogspot.com/ and using the firebug console to run these code.
Situation 1 when i use absolute container ids
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
$("#3337831342896423186,#123892177945256656,#9095347670334802803,#2525451832509945787").wrapAll('<div>');
}
};
Situation 2 when i use variable's to select the containers
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
var front_name = "#";
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
}
};
So when i use the situation 2 code then it doesn't work but the situation1 code works fine. Can anybody help me with this
You need to pass in the selector as a string, not a list of arguments;
$(joined_id_0+', '+joined_id_1+', '+joined_id_2+', '+joined_id_3).wrapAll('<div>');
Or even better, replace all of:
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
With:
$('#'+id_coll.join(', #')).wrapAll('<div>');
And remove the line: var front_name = '#';
You have to concatenat the ids, separated by a comma, as in #id1, #id2, ....
You can do that this way:
[joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')
The whole line:
$([joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')).wrapAll('<div>');
If it doesn't works, check the what is returned by [joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',') (alert() it, or use console.log).

Javascript - How do I declare a variable with the variable name based on a string?

var cur_storage_unit = $('#storage_unit').val();
$('.size_unit').change(function() {
var id = $(this).attr('id');
//This is how I want it to work, but not sure how
'cur_' + id = $(this).val();
});
The user 'changes' a of class 'size_unit' and id of 'storage_unit'. I want to then set the value of 'cur_storage_unit' to the new value of 'storage_unit'. In italics is how I want it to work, but I'm not sure the syntax of how to get it to work. Thanks!
You're probably better off using an Object, and storing it in there.
var cur_storage_unit = $('#storage_unit').val();
var values = {}; // storage for multiple values
$('.size_unit').change(function() {
var id = this.id;
values['cur_' + id] = this.value; // store this value in the "values" object
});
// Accessible via values object
alert( values["cur_theid"] );
you can create a new property on an object using a string as a key
var myObj = {};
myObj['cur_'+id] = $(this).val();
so in your case you would want an object with a known name where you can add dynamically named properties.
If it's global you can do window['cur_'+id];

Categories