I am new to JSON and struggling with the following.
I have an external JSON file
teamSkills = '[\
{"name":"John", "team":"Red"}, \
{"name":"Anna", "team":"Green"}, \
{"name":"Peter", "team":"Orange"}\
]
I want my HTML file to read the team names and populate a drop down list. From searching the web and 'playing' with the code, I now have the following JavaScript however it uses an array not the external JSON (which will contain a lot of records):
var TeamName = ["Red", "Green", "Orange"];
var sel = document.getElementById('teamList');
var fragment = document.createDocumentFragment();
TeamName.forEach(function(team, index) {
var opt = document.createElement('option');
opt.innerHTML = team;
opt.value = team;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
The HTML code:
<select id="teamList"></select>
Can this be updated to get the data from the external JSON file?
An array of objects and an array of strings are almost the same thing. You can replace TeamName with teamSkills then access the team from the inner object:
// Not sure what is the initial format of your data here,
// use JSON.parse('your string') if you have a string to start with
var teamSkills = [
{"name":"John", "team":"Red"},
{"name":"Anna", "team":"Green"},
{"name":"Peter", "team":"Orange"}
];
var sel = document.getElementById('teamList');
var fragment = document.createDocumentFragment();
// Here, iterate through the skills instead
teamSkills.forEach(function(skill, index) {
var opt = document.createElement('option');
// Here, access the team from the current skill object
opt.innerHTML = skill.team;
opt.value = skill.team;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
you can use this code it will be working good with you
$.each(TeamName, function(key, value) {
$('#teamList').append($("<option></option>").attr("value",key).text(value));
});
Sorry for using different code :
let dropdown = $('#teamList');
const teamSkills = 'https://api.myjson.com/bins/1abhwz';
// Populate dropdown with list of provinces
$.getJSON(teamSkills, function(data) {
$.each(data, function(key, entry) {
dropdown.append($('<option></option>').attr('value', entry.name).text(entry.team));
})
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="teamList"></select>
Related
I try to make dynamically multiple input with dropdown list,
My select list is using viewbag and the result is always undefined.
The Viewbag List
private void ToolCategories(object selectedcat = null)
{
var catQuery = from d in db.Toolcategories
where d.In == "AD"
orderby d.CategoryName
select d;
SelectList ToolCategories = new SelectList(catQuery, "CategoryId", "CategoryName", selectedcat);
ViewBag.ToolCategories = ToolCategories;
}
The View
#using System.Text.Json;
<script>
var resin = document.createElement("div");
resin.setAttribute("class", "col-md-4");
var resinGrup = document.createElement("div");
resinGrup.setAttribute("class", "form-grup");
var resinLabel = document.createElement("label");
resinLabel.setAttribute("class", "form-label fs-6");
resinLabel.innerHTML = "Tool";
var jsonObj = #Html.Raw(JsonSerializer.Serialize(ViewBag.ToolCategories));
var resinSelect = document.createElement("select");
resinSelect.setAttribute("id", "CategoryId");
resinSelect.setAttribute("class", "form-control");
resinSelect.setAttribute("required", "");
resinSelect.setAttribute("name", `[${toolID}].ToolCategories`);
$.each(jsonObj, function (index, ToolCategories) {
var option = document.createElement("option");
option.value = ToolCategories.CategoryId;
option.text = ToolCategories.CategoryName;
resinSelect.append(option);
})
</script>
My select list is using viewbag and the result is always undefined.
Well, your undefined dropdown is pretty obvious because you have used SelectList which keeps data as Text and Value pairs. Thus, you are binding it within your $.each loop as CategoryId andCategoryName but the items is not residing there as it is. As you can see below:
Solution:
You need to modify your option binding as option.value = ToolCategories.Value; instead of ToolCategories.CategoryId;
Thereofore, complete code would be:
$.each(jsonObj, function (index, ToolCategories) {
console.log(ToolCategories);
var option = document.createElement("option");
option.value = ToolCategories.Value;
option.text = ToolCategories.Text;
resinSelect.append(option);
});
Output:
Note: If you still need further details on it, please have a look on our official document here.
Seems everything looks fine except below 2 lines, in your view file.. Replace your Category Id with Value and CategoryName with Text.
option.value = ToolCategories.Value;
option.text = ToolCategories.Text;
You are getting undefined as it failed to find values but required values mapped to different properties.
This is the code i am using to get the array and then add them to the select object.
var select = document.getElementById('select');
var theArray = localStorage.getItem("array")
JSON.parse(theArray)
if (theArray != null){
for (var i=0; i > theArray.length; i++){
select.add(theArray[i])
}
}
Here is the code i am using to set the localStorage values.
var select = document.getElementById('select');
var option = document.createElement("option");
option.text = visText;
option.value = actVal;
select.add(option)
theArray[theArray.length+1] = option;
localStorage.setItem("array",JSON.stringify(theArray))
Can anybody tell me how to fix this?
Looks like you forgot to assign the parsed Json to a variable:
let select = document.getElementById('select')
let data = JSON.parse(localStorage.getItem('array'))
for(let entry of data) {
select.add(new Option(entry))
}
Not 100% sure if it works but should do.
You can just call the session and local storage with dot notation. The snippet below shows this. However, the snippets here are sandboxed, and cannot be written to. So, to demonstrate how to populate a select element from an array, I used a try..catch block so when it errored out, it would at least populate the select options with the original array variable.
const array = new Array(10).fill(0).map((elm, idx) => (elm = idx, elm));
let arrayFromStorage;
try {
window.localStorage.myArray = JSON.stringify(array);
arrayFromStorage = JSON.parse(window.localStorage.myArray);
} catch (error) {
console.warn(error.message)
arrayFromStorage = array;
}
arrayFromStorage.forEach(elm => {
const opt = document.createElement('option');
opt.value = elm;
opt.innerText = `option ${elm}`;
document.querySelector('select').append(opt);
})
<select></select>
If you copy/paste this into a browser console, you can see that it can be set and called using dot notation
const array = new Array(10).fill(0).map((elm, idx) => (elm = idx, elm));
let arrayFromStorage;
window.localStorage.myArray = JSON.stringify(array);
arrayFromStorage = JSON.parse(window.localStorage.myArray);
I have a big problem working with this.
I have a table in my html, in my js I'm using localstore (I have never used that before)
I insert a new row, and it is stored with localstore, I create a JSON.
For putting the ID of the raw, I just get the length of my localstorage.
For example, I have 3 rows, with IDs 1, 2 and 3.
If I decide to delete one, we can say the number 2, I can delete it, yeah, but the next time when I create a new raw I'll have the id = 2.
why?, because I use localstorage.length+1 for putting the id, so... If I had 3 before, the next time I'll get a 3, I'll replace my content where ID = 3.
what can I do for avoid that mistake?
my JS is this
crearTabla(tablastorage)
$("#btnNuevo").on('click',function(){
$("#mymodal1").modal("show");
$('#btnGuardar').data('evento','crear');
});
$("#btnCargar").on('click',function(){
crearTabla(tablastorage)
});
$("#btnGuardar").on('click',function(){
if($(this).data('evento') == "crear"){
Crear();
$('input:text').val('');
}
else{
Modificar();
}
$("#mymodal1").modal("hide");
});
function crearTabla(data){
$("#tabla").empty();
$.each(data, function(index, val){
var temp = JSON.parse(val);
var $tr = $("<tr/>");
var $tdID = crearTD(temp.id);
var $tdMatricula = crearTD(temp.matricula);
var $tdNombre = crearTD(temp.nombre);
var $tdSexo = crearTD(temp.sexo);
var $tdAccion = crearAccion(temp);
$tr.append($tdID, $tdMatricula, $tdNombre, $tdSexo, $tdAccion);
$("#tabla").append($tr);
$('input:text').val('');
})
}
function Crear(){
var $tr = $("<tr/>");
var $tdID = crearTD(tablastorage.length+1);
var $tdMatricula = crearTD($("#matricula").val());
var $tdNombre = crearTD($("#nombre").val());
var $tdSexo = crearTD($("#sexo").val());
var JSon = {
id:tablastorage.length+1,
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
if($('#matricula').val()=='' || $('#nombre').val()=='' || $('#sexo').val()==''){
alert("Uno o mas campos vacios");
}
else{
tablastorage.setItem(tablastorage.length, JSON.stringify(JSon))
var $tdAccion = crearAccion(JSon);
crearTabla(tablastorage)
$('input:text').val('');
}
};
function crearTD(texto){
return $("<td/>").text(texto);
};
function crearAccion(objeto){
var $td = $("<td/>");
var $div = $("<div/>",{
class:'btn-group',
role:'group'
});
var $btnElminar = $("<button/>",{
class:'btn btn-danger eliminar'
}).html("<i class='glyphicon glyphicon-remove'></i>"
).data('elemento',objeto);
var $btnModificar = $("<button/>",{
class:'btn btn-info modificar'
}).html("<i class='glyphicon glyphicon-pencil'></i>"
).data('elemento',objeto);
$div.append($btnElminar, $btnModificar)
return $td.append($div);
};
$("#tabla").on('click','.eliminar',function(event){
console.log($(this).data('elemento').id)
tablastorage.removeItem($(this).data('elemento').id-1)
crearTabla(tablastorage)
});
$("#tabla").on('click','.modificar',function(event){
index = $(this).data('elemento').id-1;
var $elemento = $(this).data('elemento');
$('#btnGuardar').data('evento','modificar');
$('#id').val($elemento.id);
$('#matricula').val($elemento.matricula);
$('#nombre').val($elemento.nombre);
$('#sexo').val($elemento.sexo);
$("#mymodal1").modal("show");
});
and my html have this code:
http://notes.io/wAYL
Two extra things.
1. Sorry for my bad english, If I've made a mistake is because I speak spanish, not english all the time, I need to improve my skills with the languague.
2. Also because I don't know how to put the code here. I just tried and I faild so many times.
<-- Please don't erase this -->
What i usually do is store whole arrays in one storage key as JSON.
When you load page you get whole array using something like:
var data = JSON.parse( localStorage.getItem('tableData') || "[]");
$.each(data, function(_, item){
// append html to table for each item
});
Then in your Crear() you would push the new item into the array, and store the whole array
var JSon = {
id: +new Date(),
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
data.push(JSon);
localStorage.setItem('tableData', JSON.stringify(data));
Similar to remove an item , splice() the array to remove it from main array and store again.
One suggestion for ID is use current timestamp
Hello I have a following html
<select id="fld_base_profile_id" defaultValue="-1" class="m-wrap span10" field="fld_base_profile_id" appEditor="true"></select>
I have this in my ajax
$result['analyze_type'][] = array ("id" => $row[idatabase::FIELD_ID], "name" => $row[idatabase::FIELD_PROFILE_NAME]);
echo json_encode($result);
and in js part (by the way i'm using Prototype.js) :
var JSON = transport.responseText.evalJSON();
In console, my JSON.analyze_type looks like this
Array[1]
0: Object
id: "939"
name: "Reaktif İndüktif Kontrolü Ana Profili"
The question is, how can i parse this JSON data so it can change my html like
<option value="id">name</option> ??
EDIT: Solution:
this.baseProfile = $("fld_base_profile_id");
var JSON = transport.responseText.evalJSON();
this.type = JSON.analyze_type;
for(var i = 0; i < JSON.analyze_type.length; i++) {
var profile = JSON.analyze_type[i];
var opt = document.createElement("option");
opt.value = profile.id;
opt.text = profile.name;
this.baseProfile.appendChild(opt);
}
Try this
var el = document.getElementById('fld_base_profile_id');
for(var i = 0; i < JSON.length; i++) {
var profile = JSON[i],
opt = document.createElement("option");
opt.id = profile.id;
opt.value = profile.name;
el.appendChild(opt);
}
You could do it in a much cleaner way
Firstly make sure you are passing the Content-Type: application/json header in your JSON response - All of the Ajax methods in Prototype will automatically process the response as JSON and put it into transport.responseJSON
Then your javascript can clean up to this
this.baseProfile = $("fld_base_profile_id");
var type = transport.responseJSON.analyze_type;
type.each(function(item){
var option = new Element('option',{'value':item.id}).update(item.name);
this.baseProfile.insert(option);
},this);
You can use JSON.Parse to turn the JSON you get into an object. then you can loop over the items, assign each one to an <option> object and then append them to the select.
JavaScript - populate drop down list with array explains how to create the option tags.
I've been trying this for a while now and could not find anything online...
I have a project, where tablerows get added to a table. Works fine.
Now I want to save the Table in the localStorage, so I can load it again. (overwrite the existing table).
function saveProject(){
//TODO: Implement Save functionality
var projects = [];
projects.push($('#tubes table')[0].innerHTML);
localStorage.setItem('projects', projects);
//console.log(localStorage.getItem('projects'));
The problem is the Array "projects" has (after one save) 2000+ elements. But all I want is the whole table to be saved to the first (or appending later) index.
In the end I want the different Saves to be listed on a Option element:
function loadSaveStates(){
alert('loading saved states...');
var projects = localStorage.getItem('projects');
select = document.getElementById('selectSave'); //my Dropdown
var length = projects.length,
element = null;
console.log(length);
for (var i = 0; i < length; i++) {
element = projects[i];
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = 'project ' + i;
select.appendChild(opt);
}
}
Can anyone tell me what I am doing wrong?
You can easily do this by jquery, are you interested in this, if yes.. then try following code
For setting the value
$.jStorage.set("projects", $.trim(projects));
For Getting the data
$.jStorage.get("projects");
For deleting the data with key
$.jStorage.deleteKey("projects");
I coose to stay with localStorage, but insted of using an Array I just let the user give every project a name and create a new Item for every Save:
function saveProject(){
//TODO: Implement Save functionality
var pname=prompt("Please enter your project name:","projectname")
var text = $('#mainTable')[0].innerHTML;
//console.log(text);
localStorage.setItem(pname, text);
//console.log(localStorage.key(2));
loadSaveStates();
}
function loadProject(){
var selected = $('#selectSave')[0].selectedIndex
//console.log(selected);
if (localStorage.key(selected) == 'jStorage'){
selected++;
}
var innerHTMLTable = localStorage[localStorage.key(selected)];
//console.log(innerHTMLTable);
$('#mainTable')[0].innerHTML = innerHTMLTable;
updateHandlers();
}
function deleteProject(){
var selected = $('#selectSave')[0].selectedIndex
var pname = $('#selectSave')[0].options[selected].value
$('#selectSave')[0].remove(selected);
localStorage.removeItem(pname);
//console.log(pname);
loadSaveStates();
}