Updating a Drop down list with Jquery from JSON - javascript

I have a list that I need to fill using a JSON collection of object. Here is what my action is returning:
public ActionResult GetProductCategories()
{
var categories = _entities.ProductCategories.ToList();
var result = new List<SelectListItem>();
foreach (var category in categories)
{
result.Add(new SelectListItem {Text = category.CategoryName, Value = category.CategoryId.ToString()});
}
return Json(result, JsonRequestBehavior.AllowGet);
}
This is what I've come up with for my javascript, gathered from various sources:
function loadCategories() {
$.getJSON("/Admin/Product/GetProductCategories", null, function (data) {
var selectList = $("#subCategories");
$.each(data, function(index, optionData)
{
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
});
});
}
But it doesn't appear to be working, and isn't giving any errors. Whats the best practice for this sort of thing?

I was wondering what are you trying to achieve in this next lines of codes,
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
are you trying to create an option then add it on select? if so, do it like this, use .append()
selectList.append(option);
with that, I'm still assuming new Option(optionData.Text, optionData.Value); is creating a new option, in jQuery it would be like this var option = $('<option>').text(optionData.Text).val(optionData.Value);
added notes for .add(),
var selectList = $("#subCategories"); // creates jQuery object selectList.
selectList.add(option, null); // selectList is jQuery object,
// so when you call .add(), you're calling jQuery's `add()`.
a workaround is this,
selectList[0].add(option, null); // you can use [0] to convert it into DOM object.
difference between:
DOM select object's .add()
jQuery object's .add()

JQuery fails silently if it doesn't like the JSON data coming back from the server. Point your browser at /Admin/Product/GetProductCategories and look at the result. Make sure it doesn't have any html tags and make sure there are double quotes around the key names.

Related

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

Variable for each element in array

Being a rookie at JavaScript, I stumbled upon this simple issue where I need to create an object for each item in an array.
More specifically, I want to create a WYSIWYG text editor for some textareas and then listen to these editor objects for input.
The code for one element would be:
// Make an element a text editor area.
var editorArea = new Edicy.TextEditorView({el: $('.foo')});
// Save on input
editorArea.editor.on('aftercommand:composer', function() {
pageData.set('key', 'value');
});
As I have many of these areas, I would like to use jQuery.each() to initiate these text editors and according unique listeners, using the data-id attribute of the elements:
$('#c-success-tabs-content .tab-pane').each(function(){
var successID = $(this).attr('data-id');
successesList.push(successID);
var editorArea[successID] = new Edicy.TextEditorView({el: $('.foo')});
editorArea[successID].editor.on('aftercommand:composer', function() {
pageData.set('key', 'value');
});
});
As the naming scheme "var editorArea[successID]" and from that the listener "editorArea[successID]" are not possible in JavaScript, what would be the optimum solution?
Use an object:
var editorAreas = {}
$('#c-success-tabs-content .tab-pane').each(function(){
var successID = $(this).attr('data-id');
successesList.push(successID);
editorAreas[successID] = new Edicy.TextEditorView({el: $('.foo')});
editorAreas[successID].editor.on('aftercommand:composer', function() {
pageData.set('key', 'value');
});
});
for(var id in editorAreas){
console.log(id, editorAreas[id])
}
Its just your syntax that is wrong; you can have an array of editors
var editorArea = []; // declare globally
and then
editorArea[successID] = new Edicy.TextEditorView({el: $('.foo')});

When stringifying an object, JSON turns element nodes into Objects?

So I'm working on a little personal project and I came upon a problem.
I need each day object to hold various dom element objects. These object instances are stored in an array and then that array needs to be stored into localStorage to load later.
The problem is when I do JSON.stringify and then JSON.parse it converts the HTML nodes into objects. So when I try to append element it tells me that the first parameter is not a node.
function save() {
localStorage.days = JSON.stringify(global.days);
localStorage.numberOfDays = global.numberOfDays;
localStorage.totalCount = global.totalCount;
}
function load() {
var parsedDays = JSON.parse(localStorage.days);
parsedDays.forEach(function(day){
document.getElementById("mainPage").appendChild(day.textObject);
});
anyone know how I can put an array of objects which hold elements into localStorage while keeping their node type????
If you will try to stringify dom nodes then it will return "{}".So its not possible to store node as it is inside localstorage.
What you can do is store information regarding nodes inside localstorage and recreate your node from that information and add it in your dom.
You'd probably need to have a property eg 'type' that defines the element type
var elem
parsedDays.forEach(function(day){
elem = document.getElementById("mainPage").createElement(day.type);
elem.attributes = day.attributes;
elem.innerHTML = day.textObject;
});
Or something like that, not too sure without seeing your day object
Use JSON.stringify and JSON.parse
Example Code:
Element.prototype.toJSON = function (){
return {nodeType:this.nodeType, outerHTML:this.outerHTML};
};
function replacer(k,v){
if(v.nodeType===1 && v.outerHTML){
var ele = document.createElement('html');
ele.innerHTML = v.outerHTML;
return ele.removeChild(ele.firstChild);
}
return v;
}
//test
var jstr = JSON.stringify({ele:document.body});
var json = JSON.parse(jstr,replacer);
console.log(jstr);
console.log(json);

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

Does jQuery have a collect method

I have this code
var selected = new Array();
$(".client_associates_users input:checked").each(function(index) {
selected.push($(this).val());
});
and it works great but i was wondering if jQuery had a collect so i would not have to create an array and push to it.
I basically want all the values of the checked input fields
jQuery offers the .map() method,
var selected = $(".client_associates_users input:checked").map(function(index) {
return this.value;
}).get();
This method will create a new array out of whatever data you return from within the callback. Be aware that you need to call .get() at the end to get a real array.
Ref.: .map()
Yes, $.fn.map http://api.jquery.com/map/ or $.map http://api.jquery.com/jQuery.map/
var $checkboxes = $(".client_associates_users input:checked"),
selected = $checkboxes.map(function(i){
return $checkboxes.eq(i).val();
}).get();
or this for $.map (I prefer this one)
var $checkboxes = $(".client_associates_users input:checked"),
selected = $.map($checkboxes, function(el,i){
return $checkboxes.eq(i).val();
});
Update
No longer recreates a jQuery object on each iteration.
The jQuery object $(".client_associates_users input:checked") is an array so you should just be able to access those values if you append a .val() to the end of that selector.

Categories

Resources