Append multiple options in html select at once - javascript

I want to append multiple options in html select.
Currently I'm using the below code in a loop, but it make the working slow as it have to add new option every time.
Code Snippet:
s.options[s.options.length]= new Option(url, '1');
So I guess, if I can add all the options at once and not one by one like above, maybe it can make it little faster.
Please suggest a more fast function then this one. Thanks

Try this,
s.options[s.options.length]=function Option(url,'1') {
// statements go here
};

You may be able to do it with a DocumentFragment but I'm unsure about browser support. It certainly works in current versions of all browsers (including IE 10) but I doubt it works in old IE.
var frag = document.createDocumentFragment();
for (var i = 0; i < 10; ++i) {
var option = document.createElement("option");
option.value = "" + i;
option.text = "Option " + i;
frag.appendChild(option);
}
s.appendChild(frag);
Demo: http://jsfiddle.net/QsNpe/

Try this:
var tmpOptions = [];
for(var i=0; i<optionsLength; i++) {
tmpOptions[i] = new Option(url, i);
}
s.options = tmpOptions;

try this
var dataArr = [{'value':'val1','text':'text1'},
{'value':'val2','text':'text2'},
{'value':'val3','text':'text3'},
{'value':'val4','text':'text4'},
{'value':'val5','text':'text5'},
{'value':'val6','text':'text6'},
{'value':'val7','text':'text7'}];
// Removes all options for the select box
$('#optExample option').remove();
// .each loops through the array
$.each(dataArr, function(i){
$('#optExample').append($("<option></option>")
.attr("value",dataArr[i]['value'])
.text(dataArr[i]['text']));
});

Related

Adding options to a select and using select2

I am trying to add options to a select drop down list. I am doing this dynamically with js.
When I do this with one select list it works but I need to dynamically add more select list as the user wants to add more sets.
My one list works just fine like this:
<body>
<select class="js-example-basic-single" name="state"></select>
</body>
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
load_workout_lst({{workout_list | tojson}});
let lst = {{workout_list | tojson}};
let e = document.getElementsByName('state');
console.log(e);
for(var i = 0, l = lst.length; i < l; i++){
var option2 = lst[i];
e[0].options.add(new Option(option2));
}
</script>
I notice when I console.log(e) I get a NodeList. Since I know there is only one item in that list I choose the first one. I access its options and add to it. It works great.
When I add the select menu dynamically I do this:
let exercise = $("#exercise");
var input;
var input = $("<select>").attr("type", "text").attr("name", exerciseName).attr("tabindex", tabIndexNum);
var br = $("<br>");
exercise.append(br);
exercise.append(input);
input.select2();
console.log(input);
for(var i = 0, l = workout_lst.length; i < l; i++){
console.log(workout_lst[i]);
var item = workout_lst[i];
input.options.add(new Option(item));
}
tabIndexNum++;
var workout_lst = [];
function load_workout_lst(lst){
for (let i = 0; i < lst.length; i++){
workout_lst.push(lst[i]);
}
}
Error:
Uncaught TypeError: input.options is undefined
When I console.log(input) here I get an Object. I'm sure that this is my problem I just don't know how to push or add to the Object. Is there a different way I need to be adding to an object? What am I doing wrong here?
I found the official select2 documentation very simple when it comes to managing options. For example, you can use the code snippet below to append and select option. For more details, i have left a reference.
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, true, true);
$('#mySelect2').append(newOption).trigger('change');
Reference:
https://select2.org/programmatic-control/add-select-clear-items

Select option issue

I created a small code that for some strange reason it works badly.
With the first var declare variables, but it is just to let you see for what they are, aren't declared there. Opt is an array containing all the values ​​read from a file, alunno is a select , and trovata it's a counter that tells me how many rows there are.
Everything so far works fine, but in the while loop, where am I going to perform the adding in the select if I have for example two values ​​to be loaded, the first option is replaced with the second so instead of finding myself:
John, Antoine in the select, I find:
Antoine, Antoine.
Which is quite strange considering that John is added initially, but then is replaced by the last value.
What's wrong with this code?
var opt, elaborazione;
var alunno = document.getElementById('alunno');
var trovata = 0;
while(true)
{
opt = new Option();
elaborazione = v[count].split(";");
elaborazione = elaborazione.slice(0,2);
elaborazione = elaborazione.join(" ");
opt.text = elaborazione;
alunno.add(opt);
trovata--;
if(trovata == 0){break;}
}
more details:
while(!flow.AtEndOfStream)
{
var lettura = flow.ReadLine();
opts = lettura.split(';');
count++;
v[count] = lettura;
}
You are not changing count in the loop:
while(true)
{
opt = new Option();
elaborazione = v[count].split(";"); //The count is the same here
//...
trovata--;
if(trovata == 0){break;}
}
Thus you always use the last item of v, which is always the same.

Getting selected options with querySelectorAll

I wonder if it's possible in Javascript to get the currently selected options in a <select multiple> field using the Selctors API rather than a "stupid" iteration over all options.
select.querySelectorAll('option[selected="selected"]') only returns the options that were marked as preselected in the original HTML, which is not what I'm looking for. Any ideas?
document.querySelectorAll('option:checked')
Works even on IE9 ;)
I was also experienced your issue, I have a feeling it's to do with JavaScript not recognising changes in the DOM.
Here is a solution:
jsFiddle
document.getElementById('test').onclick = function () {
var select = document.getElementById('select');
var options = getSelectedOptions(select);
console.log(options);
};
function getSelectedOptions(select) {
var result = [];
var options = select.getElementsByTagName('option');
for (var i = 0; i < options.length; i++) {
if (options[i].selected)
result.push(options[i]);
};
return result;
}
As described in
https://www.w3schools.com/jsref/prop_select_selectedindex.asp
you can get the currently selected index with
selectObject.selectedIndex
It also changes in a change eventListener.
For example:
id_selected = document.querySelector('#sel').selectedIndex;
console.log(document.querySelector('#sel')[id_selected]);

How to remove a null element in jquery?

I have an application in which i am storing values in localstorage. By default my first value is null due to which i am getting error to run the code so i want to remove the first element and continue the processes. can anyone please help me how to remove first element from list?
Piece of my code is below:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
for(var i = 0; i < mySplitResult.length; i++) {
if (.....) {
.
.
}
}
where str returns null,1,2,3,.....
I hope my question is clear can anybody help me.
This should also work:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
mySplitResult.splice(0, 1);
You can use .shift().
mySplitResult.shift()
Instead of uing the shift() function, I would suggest you to create a function that return a new clean array. This will solve even the case where there are more than one (and in any postion) null value.
You can use this solution
This should do the trick:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",").splice(1); // Remove the first item.
for(var i = 0; i < mySplitResult.length; i++) {
// Stuff
}

how do i set selected in Dojo form.select option

Hi there Dojo developers, I have a drop down form.select, and it has few options, how do set an option to be selected. Say I want to have the third option displayed in the select element. I was looking at the dojo docs and I do not see setSelected() or similar.
Thanks
You need to use displayedValue property in addition to value to set the displayed option. Use something like:
selector.set("displayedValue", "the_text_of_the_option");
or you can search the underlying store of your drop down by using :
selectorStore.fetch({query:{id: value}, onComplete: function (items) {
dojo.forEach(items, function(item){
selector.set("displayedValue", "the_text_of_the_option");
selector.set("value", "the_value_of_the_option");
});
}});
Hope that helps.
I found it, it is selector.attr("value", "the_name_of_the_option");
Thank you, this is true and working. I have tested it. However i discovered my bug: I was creating the options dynamically, and when I set .selected = true as soon as I add it to the selector it changes the sated to the first one being selected.
Or if I apply selector.set("displayedValue", "the_text_of_the_option");
It displays visually the selected one but in fact behind the selected is still the first one does not meter if I change it with the above selector.set. So I solved it by manually creating the selected state. This way when I add it letter id stays in the desired one and changes it accordingly.
Snipped here:
//populate latitude selector
match = false;
optionsArr = [];
for(var i = 0; i < namesLength; i++){
for(var j = 0, len2 = latNames.length; j < len2; j++){
if(fieldNames[i].toLowerCase() == latNames[j]){
for (var a = 0; a < namesLength; a++) {
var option = {};
option.label = fieldNames[i];
option.value = i+"";
if(i==a){
option.selected = true;
}
optionsArr.push(option);
}
match = true;
}
}
}
if(match){
var drop1 = dijit.byId("selectLatitude");
drop1.addOption(optionsArr);
}else{
var drop1 = dijit.byId("selectLatitude");
drop1.addOption(options);//options is an array of options created originally
}

Categories

Resources