Bootstrap select custom dynamic options - javascript

I am using bootstrap select and I encounter a problem when I want to add dynamic options using Javascript. The list is always empty. When I switch back to using HTML select the following Javascript code works perfectly.
HTML:
<select class="selectpicker" data-style="btn-lg btn-list-author"
id="author-list" data-live-search="true" title="Select Author"></select>
Javascript:
readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text){
data = JSON.parse(text);
$.each(data, function(i, v) {
alert(v.login);
var ul = document.getElementById("author-list");
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
});

With bootstrap-select you need to call the refresh method of the select-picker after you add new options.
Excerpt from bootstrap-select refresh Documentation:
.selectpicker('refresh')
To programmatically update a select with JavaScript, first manipulate
the select, then use the refresh method to update the UI to match the
new state. This is necessary when removing or adding options, or when
disabling/enabling a select via JavaScript.
Untested Example Using Your Original Code:
readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text) {
data = JSON.parse(text);
$.each(data, function(i, v) {
alert(v.login);
var ul = document.getElementById("author-list");
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
// Example call of 'refresh'
$('.selectpicker').selectpicker('refresh');
});
This lets bootstrap-select know of the data changes to the select element so it can redraw it's contents.
Working Example (with a modified version of your code)
Working Codepen with some modifications
Codepen Code:
// Had to create some stubs to replace missing code.
var repolink = 'silviomoreto/bootstrap-select';
function readDataFromGit (url, callback) {
$.get(url, callback);
}
//End of stubs
readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text) {
data = text; // Changed this because my stub is already returning parsed JSON.
var ul = document.getElementById("author-list"); // moved this out of the loop for a bit of performance improvement (not relevant to the solution.)
$.each(data, function(i, v) {
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
$('.selectpicker').selectpicker('refresh');
});

Here is a dynamic drop-down menu with grouped options from a data array:
// Example data Array list
namespace_list = [
['test1-c1', 'test2-c1', 'test3-c1', 'test4-c1', 'test5-c1', 'test6-c1'],
['test1-c2', 'test2-c2', 'test3-c2', 'test4-c2', 'test5-c2', 'test6-c2']
]
$('#pod_dropdown').selectpicker();
// Selecting selectpicker dropdown
select = document.getElementById('pod_dropdown');
for (let namespace of namespace_list) {
// Generating group name
namespace_name = namespace[0].slice(6, 8)+'-title'
// Creating the optiongroup
var optgroup = document.createElement('optgroup');
optgroup.id = namespace_name;
optgroup.label = namespace_name
// Appending optiongroup to the dropdown
select.appendChild(optgroup);
// Selecting the optiongroup
optiongroup = document.getElementById(namespace_name);
for (let pod of namespace) {
// Creating the options of the optiongroup
var opt = document.createElement('option');
opt.value = pod;
opt.innerHTML = pod;
// Appending the option to the optiongroup
optiongroup.appendChild(opt);
}
}
// Refresh the dropdwon menu
$('#pod_dropdown').selectpicker("refresh");
// Getting the value after selecting it in the UI and unselect the dropdown
function filterpod() {
let pod = $('#pod_dropdown').val().toString();
console.log(pod)
}
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- bootstrap -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- multi select dropdown -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<!-- Creatting the dropdown -->
<select id="pod_dropdown" class="selectpicker" data-style="btn btn-primary btn-sm" multiple data-live-search="true" data-width="auto"></select>
<!-- Calling the function filterpod when hide dropdown after select option -->
<script type="text/javascript">
$('#pod_dropdown').on('hide.bs.select', function(e) {filterpod();});
</script>

Related

HTML select options do not get populated with getElementById and innerHTML [duplicate]

I am attempting to create a bit of JavaScript that, on the click of a button, adds a tag filled with options. The options will be defined with an array called "roster". What I would like to see is a dropdown that has options for sanchez, ronaldo, and ozil.
var roster = [
"ozil",
"sanchez",
"ronaldo"
];
var reps = null;
var dropdown = null;
var scorerOption = "<option value='" + reps + "' class='scorerOption'>" + roster[reps] + "</option>";
function makeDropdown () {
dropdown = "<select class='scorer'>" + String(scorerOption).repeat(roster.length) + "</select>";
document.getElementById("rawr").innerHTML = dropdown;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="rawr"><button onclick="makeDropdown()">Select a player</button></p>
</body>
</html>
As you may notice, the and tags appear, but all have innerHTML's and values of "undefined". How can I change that so it displays the names sanchez, ronaldo, and ozil?
You'll need to loop through the array and for each element in the array, create and insert a new option.
You should also not use inline HTML event handling attributes (onclick), see here for why.
Lastly, it's generally better to create dynamic elements with the DOM API call of document.createElement(), rather than build up strings of HTML as the strings can become difficult to manage and the DOM API provides a clean object-oriented way to configure your newly created elements.
var roster = [
"ozil",
"sanchez",
"ronaldo"
];
// Work with your DOM elements in JavaScript, not HTML
var btn = document.getElementById("btn");
btn.addEventListener("click", makeDropdown);
function makeDropdown () {
// Dynamically generate a new <select> element as an object in memory
var list = document.createElement("select");
// Configure the CSS class for the element
list.classList.add("scorer");
// Loop over each of the array elements
roster.forEach(function(item){
// Dynamically create and configure an <option> for each
var opt = document.createElement("option");
opt.classList.add("scorerOption");
opt.textContent = item;
// Add the <option> to the <select>
list.appendChild(opt);
});
// Add the <select> to the document
document.getElementById("rawr").appendChild(list);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="rawr"><button id="btn">Select a player</button></p>
</body>
</html>

How to create a drop down menu with values from spreadsheet?

I'm trying to create a drop down menu and the values inside are in a specific column of a spreadsheet.
I tried making cells with foo but i don't know how to call them to my html file. Is this efficient? Or can you show me another way to call them to my html file.
Tried this code but no idea on how to return this to html.
function email_dropdown(divname)
{
var open_sheet = SpreadsheetApp.openByUrl(')getSheetByName');
SpreadsheetApp.setActiveSpreadsheet(open_sheet);
var active_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('*********');
active_sheet.activate();
var dropdown = "<select id = 'email_dropdown'> Email";
var row_val = active_sheet.getRange("**").getValues();
var row_length = row_val.length;
var row_data = active_sheet.getRange("**");
for (var row = 2; row <= row_length; row++)
{
dropdown = dropdown + row_data.getCell(**).getValue();
}
dropdown = dropdown + "</select>"
Logger.log(dropdown);
}
Cool, You have gotten most of this solved :) Now you need to do something like the following since you have the values in the array
function yourTestfunction() {
var exampleValues = ['one', 'two', 'three'];
// after your values have been stored in the array
var sheetValuesEl = document.querySelector("#js_sheetValues");
// populate select with values
for(var i = 0; i < exampleValues.length; i++) {
// Create the option
var optionValue = document.createElement("option");
// Set the option text
optionValue.textContent = exampleValues[i];
// Add the option to the select drop down
sheetValuesEl.appendChild(optionValue);
}
}
yourTestfunction()
<select id="js_sheetValues"></select>

find values of custom attribute in html using Jquery

Click here for code
Inside loop of {listOfValue}
i want to find different column values filtered by data-week = {listofvalueObject}
and want to add data in each row based on column segregated by this data-week attributes value.
I have assigned the values form a list so it every column has different data-week value.
I have tried :
var allColumnValClass = j$('.columnVal').filter('[data-week]');
var allColumnValClass = j$('.columnVal').filter('[data-week='Something dynamic ']');
You should be able to select them like this:
var allColumnValClass = j$('.columnVal[data-week]')
and
var allColumnValClass = j$('.columnVal[data-week="' + Something dynamic + '"]')
Hope this helps.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='columnVal' data-week="1"></div>
<div class='columnVal' data-week="2"></div>
<div class='columnVal' data-week="3"></div>
<script>
var dataList = $(".columnVal").map(function () {
return $(this).data("week");
}).get();
for (var i = 0; i < dataList.length; i++) {
console.log(dataList[i]);
}
</script>
cheers

jquery- On onchange event tab content is not getting displayed properly

Below is my HTML code:
<select id="sourceNameDropdownId" label="condition " style="width:300px;">
</select>
<div id="tabs" class="selector">
</div>
Here, is my javascript code:
$("#DropdownId").change(function () {
var sid= $("#DropdownId option:selected").text();
afterclick(sid);
});
I am calling an onchange event on dropdown list, and the selected value i am passing to function afterclick
function afterclick(sid){
var tabsContainer = document.getElementById("tabs");
var crawlTab=document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList=["name1","name2","name3","name4"];
$.each(crawlList, function( index, crawlType ) {
var crawlTabElement=document.createElement("li");
crawlTabElement.innerHTML= '' +crawlType+'';
crawlTab.appendChild(crawlTabElement);
});
tabsContainer.appendChild(crawlTab);
var count=1;var tabCount=1;
$.each(crawlList, function( index, crawlType ) {
var contentCrawlTab=document.createElement("div");
contentCrawlTab.setAttribute("id",crawlType);
var p='<p>'+crawlType+'</p>';
contentCrawlTab.innerHTML=p;
tabsContainer.appendChild(contentCrawlTab);
});
$( ".selector" ).tabs();
}
This code is working fine when for the first time page gets loaded and a value is selected from the dropdown, but when i re-select value from the dropdown tabs are not getting displayed properly.
This is when i select value for the first time after page is loaded.
And when i reselect the value from dropdown its showing like this-
Is there something like reload to reload the tabs div entirely, as it seems that its appending the previous values and next time when afterclick function is called tab elements are not getting displayed properly.
I tried clearing the "tabs" div too, using **$( "#tabs " ).empty()**But it didn't worked for me.
Please help me out.
Check this working code.
$().ready(function () {
$(".selector").tabs();
$("#DropdownId").change(function () {
var sid = $("#DropdownId option:selected").text();
afterclick(sid);
});
});
function afterclick(sid) {
var tabsContainer = document.getElementById("tabs");
tabsContainer.innerHTML = '';
var crawlTab = document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList = [sid + "1", sid + "2", sid + "3", sid + "4"];
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var crawlTabElement = document.createElement("li");
crawlTabElement.innerHTML = '' + crawlType + '';
crawlTab.appendChild(crawlTabElement);
}
});
tabsContainer.appendChild(crawlTab);
var count = 1; var tabCount = 1;
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var contentCrawlTab = document.createElement("div");
contentCrawlTab.setAttribute("id", crawlType);
var p = '<p>' + crawlType + '</p>';
contentCrawlTab.innerHTML = p;
tabsContainer.appendChild(contentCrawlTab);
}
});
$(".selector").tabs('destroy');
$(".selector").tabs();
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="DropdownId" label="condition " style="width:300px;">
<option selected="selected" disabled="disabled">--Select--</option>
<option>Bilna-ID</option>
<option>IndiatimesShopping</option>
</select>
<div id="tabs" class="selector">
</div>

How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown

How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown and assigning key/values to the options using JavaScript?
Thanks
It would be easier if you use JQuery... This is how it would be done in basic Javascript.
<html>
<body>
<span id="selectContainer"></span>
</body>
<script type="text/javascript">
var selectItems = {
me: "Hari Gangadharan",
friend1: "Asif Aktar",
friend2: "Jay Thomas",
friend3: "John Abrams"
}
selectItems["newFriend"] = "Niel Goldman";
var selectContainer = document.getElementById("selectContainer");
var selectBox = document.createElement("SELECT");
selectBox.id = selectBox.name = "friendList";
selectContainer.appendChild(selectBox);
for (var key in selectItems) {
var value = selectItems[key];
var option = document.createElement("OPTION");
option.text = value;
option.value = key;
selectBox.options.add(option);
}
</script>
</html>
You're not looking for an array for this, you should use an object, for instance :
var list = {"some option": 1, "another option": 2, "etc": 3};
To therefore insert these to a dropdown you could append it to an existing option list by doing
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
Combined the code may look something like :
<script type="text/javascript">
var options = {"some option": 1, "another option": 2, "etc": 3};
window.onload = function() {
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
}
</script>
<select id="listName">
</select>
I hope that helps, it should be more than enough for you to get started.
Edit : You should obviously note that doing window.onload and replacing it with a function like that may cause undesired effects if you have existing code, so either make use of your existing library's loaded functions etc

Categories