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.
Related
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'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>
I fill a combobox via Javascript as follows:
let option = document.createElement("option");
option.innerHTML = elem.businessObject.get('id');
option.value = elem.businessObject.get('id');
taskTypeEl.appendChild(option);
whereby taskTypeE1 refers to the select - tag from my html-code
but unfortunately, I fill my combobox with a lot of duplicates. Is there an easy way
to get rid of that, such that every item only appears once?
Thanks in advance and kind regards
You can define a dictionary before starting the insertion of options, and only add the ones with the values that were not added before:
let dictionary = {}; //initiate
So when iterating to add the options, you can check if it is unique like this:
if(!dictionary[elem.businessObject.get('id')]){ //check for prev insertion
let option = document.createElement("option");
option.innerHTML = elem.businessObject.get('id');
option.value = elem.businessObject.get('id');
taskTypeEl.appendChild(option);
dictionary[elem.businessObject.get('id')] = option; //add option
}
Suppose there is a select menu like this:"
<select id="dropDown"></select>
And I wish to populate it with an array value ["apple","mango","banana"];
How can this be achieved at one go without using any looping construct?
Here you can do like
var arr = ["apple", "mango", "banana"];
document.getElementById('dropdown').innerHTML =
'<option>' + arr.join('</option><option>') + '</option>';
JSFiddle
Without the use of a loop, you would do something like this:
var x = document.getElementById("dropDown");
var option = document.createElement("option");
option.innerHTML = "apple";
x.appendChild(option);
option = document.createElement("option");
option.innerHTML = "mango";
x.appendChild(option);
option = document.createElement("option");
option.innerHTML = "banana";
x.appendChild(option);
Obviously this assumes you know what the array values are going to be ahead of time. The most common way of doing this however would be to use a loop to iterate over the array.
If you just mean not using looping construct like for/while:
document.getElementById('dropDown').innerHTML = ["apple","mango","banana"].map(function(e) {
return "<option>"+e+"</option>";
}).join('');
The demo.
You'll want to do this:
var options = ["apple","mango","banana"],
select = document.getElementById('dropDown');
for(var i = 0; i < options.length; i++){
var option = document.createElement("option");
option.value = option.innerHTML = options[i];
select.appendChild(option);
}
The "No loops" requirement is really a bad idea. This is the most efficient way to build the list, in native JS. (Aside from micro optimizations in the loop)
It also doesn't use innerHTML on DOM elements that are rendered already, avoiding the need for the browser to re-structure the entire DOM.
I have a text file which I am reading and storing the data in a javascript array, it's a list of cuisines. I want to use the array to fill up a drop down select box. I know how to hard code in the values for the drop down box (using correct me if i'm wrong) but I want to be able to use the array to fill it up instead.
<script type="text/javascript">
var cuisines = ["Chinese","Indian"];
</script>
<select id="CusineList"></select>
I have hard coded an array for simplicity, the "CuisineList" is my drop down box
Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
DEMO
UPDATE: Using createDocumentFragment and forEach
If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();
cuisines.forEach(function(cuisine, index) {
var opt = document.createElement('option');
opt.innerHTML = cuisine;
opt.value = cuisine;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
DEMO
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.