Multidimensional Array in javascript -
i have this:
var selectathing = { "id" : "productname" , "5" : "abc" , "29" : "efg" , "28" : "hij" , "11" : "xyz" "23" : "efg" , "15" : "hij" , "40" : "xyz" }; $.each(selectathing, function(key, value) { $('.myselect') .append($('<option>', { value : key }) .text(value)); });
now showing this:
<select> <option value="5">abc</option> <option value="11">abc</option> <option value="15">abc</option> <option value="23">abc</option> <option value="28">abc</option> <option value="29">abc</option> <option value="40">abc</option> </select>
this list of used multiple time in form.
so, created js array , load on every select list require.
now added importance level on each row. if level 1 show first on select list.
var selectathing = { level : [ "id" : "thingname", "id" : "thingname"] }; var selectathing = { 1 : [ "5" : "abc", "29" : "efg"], 2 : [ "28" : "hij" , "11" : "xyz"], 3 : [ "23" : "efg" , "15" : "hij" , "40" : "xyz"] };
with importance level, want show importannt content on top on select list, order first level, next id. this:
<select> <!-- importance level 1 --> <option value="5">abc</option> <option value="29">abc</option> <!-- importance level 2 --> <option value="28">abc</option> <option value="11">abc</option> <!-- importance level 3 --> <option value="23">abc</option> <option value="15">abc</option> <option value="40">abc</option> </select>
now not sure how going convert array select list or array right!
:(
help!
advance thanks!
your data structures not make sense , should reconsider layout.
think resembles database table:
var selectathing = [ {id: "5", name: "abc"}, {id: "29", name: "efg"}, {id: "28", name: "hij"}, {id: "11", name: "xyz"}, {id: "23", name: "efg"}, {id: "15", name: "hij"}, {id: "40", name: "xyz"} ]; selectathing.sort(function (a, b) { return sortalpha(a.name, b.name); }); $.each(selectathing, function(i, thing) { $('<option>', { value: thing.id, text: thing.name }).appendto('.myselect'); });
extending priorities or other attribute becomes trivial:
var selectathing = [ {id: "15", name: "hij", priority: 3}, {id: "23", name: "efg", priority: 3}, {id: "40", name: "xyz", priority: 3}, {id: "28", name: "hij", priority: 2}, {id: "11", name: "xyz", priority: 2}, {id: "5", name: "abc", priority: 1}, {id: "29", name: "efg", priority: 1} ]; selectathing.sort(function (a, b) { if (a.priority === b.priority) { return sortalpha(a.name, b.name); } else { return sortnum(a.priority, b.priority); } }); $.each(selectathing, function(i, thing) { $('<option>', {value: thing.id, text: thing.name}).appendto('.myselect'); });
helpers:
function sortalpha(a, b) { = a.tolowercase(); b = b.tolowercase(); if (a < b) return -1; if (a > b) return 1; return 0; } function sortnum(a, b) { = parsefloat(a); b = parsefloat(b); if (a < b) return -1; if (a > b) return 1; return 0; }
Comments
Post a Comment