How to make an Option Object be selected as the Default Value - javascript

The following code triggers just before a page is loaded. Now I've managed to fill a select with values. But I'm not sure on how to make the first value to be the deafault selected value.
$(document).on('pagebeforeshow', '#searchpage',
//This function is the whole function that runs when the pagebefore event occurs
function () {
//This reads the universities from the api we created
$.getJSON(AddressAccess + "Home/university/format/json",
function (data) {
//The data is sent back in a collection of objects. We need to extract each object and do relative operations
for (var i = 0; i < data.length; i++) {
var university = data[i];
var SelectDropDown = document.getElementById("searchuniversity");
var NewOption = new Option(university.Name, university.UniverstiyID);
if (i == 1) {
SelectDropDown.add(NewOption, Selected);
} else {
SelectDropDown.add(NewOption);
}
};
});
});
Now if i use SelectDropDown.add(NewOption,Selected); Only one option is made as an option in the select and what I want is to just make the first option being read from my json data to be the default option appearing in the select.

Set selectedIndex of SelectDropDown to 1:
if (i == 1) {
SelectDropDown.add(NewOption);
SelectDropDown.selectedIndex = 1;
}
If you're really talking about the very first option from the options list, selectedIndex should be 0. The options array of a select element is zero based.
[edit] based on your comment:
maybe the select already contains a blank option. Try:
if (i < 1) {
SelectDropDown.options.length = 0;
SelectDropDown.add(NewOption);
SelectDropDown.selectedIndex = 0;
}

Just set the defaultSelected property of the element to true:
var newOption = new Option(university.Name, university.UniverstiyID);
newOption.defaultSelected = true;
Or use the parameters of the Option constructor:
var newOption = new Option(university.Name, university.UniverstiyID, true, true);

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

How do you get the value of the selected option from a dynamically created select element?

I have a button to dynamically create select elements, which i created like this:
var units = units_array[0];
//ingredient unit of measurement drop down
var cell3= row.insertCell(2);
var unit_of_measure = document.createElement("select");
unit_of_measure.name = "unit_of_measure_select";
cell3.appendChild(unit_of_measure);
//Create and append the options
for (var i = 0; i < units.length; i++) {
var option = document.createElement("option");
option.value = units[i];
option.text = units[i];
unit_of_measure.appendChild(option);
}
However, when I select it inside (inside a loop from another function) i get this error in the console:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Here is the code i am using to get to the select element which sits inside a table.
var table = document.getElementById('selected_ingredients');
var rowCount = table.rows.length; //empty table has 2 rows (header + something else?)
var cellsCount = table.rows[0].cells.length -1 ; //table width in cells by counting headers minus the last cell (delete)
for (var r = 1; r < rowCount; r++) { //loop through all rows (r) in table
var $ingredient_dict = {}; //initiate dictionary for this ingredient
for (var c = 0; c < cellsCount; c++) { //loop through each cell (c) in row
var $cell = table.rows[r].cells[c];
if ($cell.innerHTML.includes("select")) { //if its is 3rd iteration (3rd cell along = select box)
alert("test");
//not working - undefined value from generated select element
var UOM = $cell.options[$cell.selectedIndex].value;
alert(UOM);
I would like to return the value of the selected option in var UOM. I'm relatively new to js so apologies if this is simple.
in your if statement you can grab a handle to the select element:
$select = $cell.querySelector('select');
//then to grab the option and value
var UOM = $select.selectedOptions[0].value;
alert(UOM);
I would also recommend that in your if statement instead of checking for text in the innerHTML you:
$cell.querySelector('select');
This will return null which is the equivalent of false if no select element is present, but return true when an element is present. The advantage is that if one of the cells contains the word 'select' for whatever reason if you are checking for the string 'select' it will return true and try to select the element that does not exist, however if you are looking for an element you just found it. Hope this helps.

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
}

Javascript helper method for generating select tag based on provided values

I am trying to create a helper method in my JS toolkit that looks like this
var selectOptionValues = [" ","NA","Yes","No"];
var selectedValue = "No";
function CreateSelectList(selectId,selectOptionValues,selectedValue){
// build the selectlist
// if the selectedValue is not null make this value selected
// return select tag
}
I am tried to do something like selectedOption = selectTag[selectedValue] and then selecteOption.selected = true but its not working.
Assuming you're generating option by creating DOM nodes and the part that isn't working, is the selected state of the No option. Try selectOption.setAttribute("selected","selected") - roughly...
var selectOptionValues = [" ","NA","Yes","No"], selectedValue = "No";
function CreateSelectList(selectId,selectOptionValues,selectedValue){
var selectList = document.createElement("select"), selectOption;
for (var i=0, totalOptions = selectOptionValues.length; i < totalOptions ; i++) {
selectOption = document.createElement("option");
selectOption.value = selectOptionValues[i];
selectOption.innerText = selectOptionValues[i];
if (selectOptionValues[i] == selectedValue) {
selectOption.setAttribute("selected","selected");
}
selectList.appendChild(selectOption);
};
return selectList;
}
In addition to method Dean Burge suggested, you can also set the default value by selectedIndex property of select object. If you make selectedValue the index of desired value, it becomes pretty simple:
//selectedValue==3;
yourPopulatedSelect.selectedIndex=selectedValue;
//"No" will be selected

How can I restore the order of an (incomplete) select list to its original order?

I have two Select lists, between which you can move selected options. You can also move options up and down in the right list.
When I move options back over to the left list, I would like them to retain their original position in the list order, even if the list is missing some original options. This is solely for the purpose of making the list more convenient for the user.
I am currently defining an array with the original Select list onload.
What would be the best way to implement this?
You can store the original order in an array, and when inserting back, determine what's the latest element in the array that precedes the one to be inserted AND matches what's currently in the select list. Then insert after that.
A better solution is to just store the old array whole and re-populate on every insertion with desired elements as follows (warning: code not tested)
function init(selectId) {
var s = document.getElementById(selectId);
select_defaults[selectId] = [];
select_on[selectId] = [];
for (var i = 0; i < s.options.length; i++) {
select_defaults[selectId][i] = s.options[i];
select_on[selectId][i] = 1;
var value = list.options[i].value;
select_map_values[selectId][value] = i if you wish to add/remove by value.
var id = list.options[i].id; // if ID is defined for all options
select_map_ids[selectId][id] = i if you wish to add/remove by id.
}
}
function switch(selectId, num, id, value, to_add) { // You can pass number, value or id
if (num == null) {
if (id != null) {
num = select_map_ids[selectId][id]; // check if empty?
} else {
num = select_map_values[selectId][value]; // check if empty?
}
}
var old = select_on[selectId][num];
var newOption = (to_add) : 1 : 0;
if (old != newOption) {
select_on[selectId][num] = newOption;
redraw(selectId);
}
}
function add(selectId, num, id, value) {
switch(selectId, num, id, value, 1);
}
function remove(selectId, num, id, value) {
switch(selectId, num, id, value, 0);
}
function redraw(selectId) {
var s = document.getElementById(selectId);
s.options.length = 0; // empty out
for (var i = 0; i < select_on[selectId].length; i++) {
// can use global "initial_length" stored in init() instead of select_on[selectId].length
if (select_on[selectId][i] == 1) {
s.options.push(select_defaults[selectId][i]);
}
}
}
I would assign ascending values to the items so that you can insert an item back in the right place. The assigned value stays with the item no matter which list it's in.

Categories

Resources