JSON 2D key value Response Text into Drop Down - javascript

I'm getting Response string same as like this.
var txtResponse = "{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}";
Need to put this on html drop down and assign Text as 'Given Name' and value as 'Employee Number' of each employee by java script.
I have used this to assign values to drop down for other array.
var select = document.getElementById("selectelement");
var optionContent = document.createElement("option");
optionContent.textContent = "";
optionContent.value = "";
select.appendChild(optionContent);
can you please help me to assign 'textContent' and 'value' from above response through loop.

You can iterate through all the keys in the json object like the following,
var txtResponse = '{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
var jsonResponse = JSON.parse(txtResponse);
var select = document.getElementById("selectelement");
Object.keys(jsonResponse).forEach(key => {
var optionContent = document.createElement("option");
optionContent.textContent = jsonResponse[key]['Given Name'];
optionContent.value = jsonResponse[key]['Employee Number'];
select.appendChild(optionContent);
})

let res:any='{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
this.res=JSON.parse(this.res);
console.log('res==',this.res)
let select=document.getElementById("selectelement");
for(let el in this.res){
let optionContent=document.createElement("option");
optionContent.innerHTML=this.res[el]['Given Name'];
optionContent.value=this.res[el]['Employee Number'];
select.appendChild(optionContent);
}
<select id="selectelement"> </select>

Related

Viewbag Dropdown list from javascript always undefined

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.

How do i store an array in localstorage and then get the contents and then add them to a select object

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);

Manipulate CQL params from database in javascript

I store CQL filtering params as varchar in the database which i have to manipulate in JavaScript. street_desc is a variable in javascript. How can i assign it to the string dynamically?
Whatever is inside the input_params has to replace the cql_param string
var street_desc= "whatever"; //input from the user
var town_code = "whatever2"; //input from the user
var cql_param= "roadname_gr='street_desc'&towndesc is not null&town_code='town_code'"; //comes from database
var input_params = [street_desc,town_code]; //declare input params to replace the cql string
The output should be:
"roadname_gr='whatever'&towndesc is not null&town_code='whatever2'";
What i have tried...
var street_desc = "whatever"; //input from the user
var town_code = "whatever2"; //input from the user
var cql_param = "roadname_gr='street_desc'&towndesc is not null&town_code='town_code'"; //comes from database
var input_params = {
street_desc: street_desc,
town_code: town_code
}; //declare input params to replace the cql string
for (const [key, value] of Object.entries(input_params)) {
console.log(`${key}: ${value}`);
cql_param.replace(key, value);
}
I update my answer to use a reducer
let cql_param= "roadname_gr='street_desc'&towndesc is not null&town_code=1";
var street_desc= "whatever"; //input from the user
var town_code = "whatever2"; //input from the user
var input_params = [street_desc,town_code];
var input_params_names = ["street_desc","1"];
let i =0;
const result = input_params.reduce((ac,c)=>{
return ac.replace(input_params_names[i++], c);
},cql_param)
console.log(result)
I managed to solve it. Here is what i did:
Declare an object with my input params i want to replace. Iterate over the key-value pairs and replace the string.
var street_desc_inp = "whatever"; //input from the user
var town_code_inp = "whatever2"; //input from the user
var cql_param = "roadname_gr='street_desc_inp'&towndesc is not null&town_code='town_code_inp'"; //comes from database
console.log(cql_param)
var input_params = { //declare input params to replace the cql string
street_desc_inp: street_desc_inp,
town_code_inp: town_code_inp
};
for (const [key, value] of Object.entries(input_params))
cql_param = cql_param.replace(key, value);
console.log(cql_param)

Filling out Combobox Using JSON value

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.

Get value from dynamically created checkboxes if checked

I made few checkboxes along with a button which on submit calls a function where I want to get all the values of checkboxes which have been checked.
Code for creating those checkboxes is:
for (var loop=0; loop < count; loop++)
{
var chap = document.createElement("input");
chap.type = "checkbox";
chap.value = nearby[loop];
chap.id = nearby[loop];
document.getElementById("mapdisplay").appendChild(chap);
var nearo = nearby[loop];
var s = document.getElementById("mapdisplay");
var text = document.createTextNode(nearby[loop]);
s.appendChild(text);
var br = document.createElement('br');
s.appendChild(br);
}
Now I want to retrieve the values which are checked. I am trying this (but to no available)
function fsearch()
{
var p = x;
var narr = new Array();
narr=nearby;//a global arr
var checked_vals = new Array();
$('#mapdisplay input:checkbox:checked').foreach()
{
checked_vals.push(this.value);
}
Please suggest something to retrieve the checked values id of generated values are in array form. I can not use $("#nearby[0]").val().
var checkedCheckBoxesValueArray = $('#mapdisplay input:checkbox:checked').map(
function(){
return this.value;
}).get();
Correct syntax would be:
$('#mapdisplay input:checkbox:checked').each(function(index) {
checked_vals.push($(this).val());
});
Live test case: http://jsfiddle.net/e6Sr3/

Categories