bootstrap 4 selectpicker how to add 'subtext' dynamically - javascript

Working with Bootstrap-4 I'm trying to dynamically add 'data-subtext' next to all the option texts of a selectpicker. Using the below code is ok with creating the list of options out of the array. But I failed to find how to add the data-subtext text as well.
Here is the relevant code:
<!---HTML part,use function to insert list of options ------>
<div class="form-group mr-2">
<div class="col-mr-2">
<div class="input-group">
<div class="input-group-append">
<select class="selectpicker w-100" data-show-subtext="true" data-live-search="true" id="buttNameSel" name="buttNameF" onChange="replacButtName()">
<option data-subtext="mysubtext_list" >select-from:</option>
<!------ autofill the options---------->
</select>
</div>
</div>
</div>
</div>
<script type="text/javascript" >
// set option list of names
selButtname = document.getElementById( 'buttNameSel' );
var opt;
for (i=0; i < nItems;i++) {
buttName = ButtNamesSplitList[i];
opt = document.createElement("option");
opt.text=buttName ;
selButtname.add(opt);
}
$('.selectpicker').selectpicker('refresh');
</script>

You an update your code to add the attribute like this:
<script type="text/javascript" >
// set option list of names
selButtname = document.getElementById( 'buttNameSel' );
var opt;
for (i=0; i < nItems;i++) {
buttName = ButtNamesSplitList[i];
opt = document.createElement("option");
opt.text=buttName ;
opt.setAttribute("data-subtext", "your_sub_text"); //add subtext here
selButtname.add(opt);
}
$('.selectpicker').selectpicker('refresh');
</script>
You can find more information how setAttribute works from this documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

Related

Run javascript code after template load and populate data from Google Sheet

I’m trying to create a web app, using Google Apps Script, in which when the the the certain condition are met, it will enable the Select Element with id="posAppDesired" then it will run the Google Apps Script to get the array of options, then return the array to the JavaScript and change the innerHTML of the Select Element. Then if the button with the id="addPositionId" is clicked, it will add a template and then it should load or duplicate the same option.
Here is the HTML code:
<!-- POSITION APPLIED FOR-->
<div class="form-row">
<div class="form-group col-sm-9">
<label for="posAppDesired">Select Desired Position</label>
<div class="input-group">
<select class="custom-select" id="posAppDesired" disabled>
<option selecte disabled>Choose...</option>
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="addPositionId"disabled>Add</button>
</div>
</div>
</div>
</div>
<!-- FOR TEMPLATE -->
<div class="form-row" id="desiredPosition"></div>
<!-- MY TEMPLATE -->
<template id="positionApplied">
<div class="form-group col-sm-9 posLine">
<div class="input-group">
<select class="custom-select templatePositionClass" id="templatePosition" aria-label="Example select with button addon">
<option selected>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary addPosButton" type="button">Add</button>
<button class="btn btn-outline-secondary removePosButton" type="button">Remove</button>
</div>
</div>
</div>
</template>
My JavaScript code:
<script>
var arrayOfPositions;
var currentlyAddedPositions = [];
document.getElementById("addPositionId").addEventListener("click", displayAddPosition);
document.getElementById("desiredPosition").addEventListener("click", afterDesiredPositionClicked);
function conditionOKAY(){
var rollNum = document.getElementById("rnum").value;
var appCat = document.getElementById("posCat").value;
document.getElementById("posAppDesired").disabled = false;
document.getElementById("addPositionId").disabled = false;
google.script.run.withSuccessHandler(positionCategoryCheck).getPositionCategory(IDNum, appCat);
}
function positionCategoryCheck(returnedPositions){
arrayOfPositions = returnedPositions.filter(function(r){ return true; });
var positionApplying = document.getElementById("posAppDesired");
uniquePositions(positionApplying, arrayOfPositions, 0);
}
function uniquePositions(el, arrayOfPositions, index){
// var currentlyAddedPositions = [];
el.innerHTML = '<option selected disabled style="font-color: #B0B0B0;" value=""> Select Desired Station</option>';
arrayOfPositions.forEach(function(r){
if(currentlyAddedPositions.indexOf(r[index]) === -1){
var option = document.createElement("option");
option.textContent = r[index];
el.appendChild(option);
currentlyAddedPositions.push(r[index]);
}
});
}
//------FOR DESIRED POSITION/S----////
function displayAddPosition(arrayOfPositions){
var addPosition = document.getElementById("desiredPosition");
var positionTemplate = document.getElementById("positionApplied");
var copyTemplate = positionTemplate.content.cloneNode(true);
addPosition.appendChild(copyTemplate);
var testPost = document.querySelector(".templatePositionClass").closest(".posLine");
var copiedPost = [];
testPost.innerHTML = '<option selected disabled style="font-color: #B0B0B0;" value=""> Select Desired Station</option>';
currentlyAddedPositions.forEach(function(r){
if(copiedPost.indexOf(r) === -1){
var option = document.createElement("option");
option.textContent = r;
testPost.appendChild(option);
copiedPost.push(r[0]);
}
});
}
function removePosition(){
document.getElementById("desiredPosition")
}
function afterDesiredPositionClicked(e){
if (e.target.matches(".addPosButton *, .addPosButton")){
displayAddPosition();
} else if (e.target.matches(".removePosButton *, .removePosButton")){
e.target.closest(".posLine").remove();
}
}
</script>
My Google Apps Script code:
function getPositionCategory(IDNum, appCat){
if(appCat == "Main"){
const ss = SpreadsheetApp.openByUrl(urlPrequalData);
const ws = ss.getSheetByName("VacantPositions");
const posSelection = ws.getRange(1,1,1, ws.getLastColumn()).getValues()[0];
var index = posSelection.indexOf(appCat)+1;
var posValues = ws.getRange(2, index, ws.getLastRow()-1, 1).getValues();
return posValues;
}
The JavaScript code above was able to add the template, and then change the innerHTML of the option element of that template. But if I click the add button again, the option element of the additional template does not change.
My aim is every time I clicked the "Add" button, it will load the template and right after the template loads, change the option in the Select Element of that template.

How to make dependent dropdown list from Google Sheet?

I have a Google sheet with custom HTML form. The form contains two <select> elements.
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="category_name">Категория</label>
</div>
<select class="custom-select" id="category_name" name="category_name" required>
<option value="" selected></option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="contragent_name">Контрагент</label>
</div>
<select class="custom-select" id="contragent_name" name="contragent_name">
<option value="" selected></option>
</select>
</div>
I want to get dependent dropdown list at the second selection (contragent_name).
Just two lists:
first: if selected value of category_name is not equal to 'Заработная Плата' --> contragent_name selection list must be populated with getContragent() (just values of one column)
second: if selected value of category_name is equal to 'Заработная Плата' --> contragent_name selection list must be populated with getStaffList() (just array with names) with required attribute.
I tried to write script but it does not work
<script>
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("category_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.value = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getCategory();
}());
$(function() {
$('#category_name').on("change", function () {
if ($(this).val() !== 'Заработная Плата') {
function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("contragent_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.value = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getContragent();
}()} else {
function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("contragent_name");
select.required = true;
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.value = selectList[i];
option.text = selectList[i];
select.add(option);
}
}
).getStuffList();
}()}
});
});
</script>
Where I'm wrong and how to fix it?
HTML
<!DOCTYPE html>
<html>
<head>
<title>My Dependent Dropdown</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<form>
<div class="form-group col-md-4">
<label for="category">Category</label>
<select id="category" class="form-control" required>
</select>
</div>
<div class="form-group col-md-4">
<label for="items">Items</label>
<select id="items" class="form-control" required>
</select>
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</body>
</html>
JS
var db = [["Vegetable","Carrot"],["Vegetable","Onion"],["Fruit","Apple"],["Fruit","Banana"]];
$(document).ready(function(){
var categoryLists = db.map(x => x[0]);
categoryLists = [... new Set(categoryLists)]; //get unique category values
categoryLists.forEach(x => $("#category").append(new Option(x, x))); //new Option("text", "value")
$("#category").on("change",updateItemLists).change(); //add event listner and trigger it once to show items
});
function updateItemLists(){
var category = $("option:selected", this).text(); //get category
var itemLists = db.filter(x => x[0] == category).map(x =>x[1]);
$("#items option").remove();
itemLists.forEach( (x, i) => $("#items").append(new Option(x,i))); //x: array value ; i: array index
};

How to receive in JS selections from html using select2

I want to receive in JS the selected values from html. In html I'm using multi-select box with selected2 library. I was able to do it for a normal single choice such as <select class="form-control" id="companies" >.
Could anybody tell me how to do it for a multiple selects with select2?
html
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<form>
<div class="form-group">
<label>Airline companies</label>
<p>
<select class="js-example-basic-multiple" id="companies" name="states[]" multiple="multiple" style="width: 120%">
<!-- select class="form-control" id="companies" --> // if I don't use multiple select with select2, it worked
<option selected>Select companies</option>
<option value="one">First</option>
<option value="two">Second</option>
...
</select>
</p>
</div>
<button class="btn btn-primary" type='button' id="button">Refresh</button>
</form>
JS
company = getSelectedOption('companies')
function getSelectedOption(id){
/* function to get the selected value from the dropdowns */
let select = document.getElementById(id);
let value = select.options[select.selectedIndex].value;
return value
}
You can get selected value by using jQuery method .val():
var company = getSelectedOption('companies');
function getSelectedOption(id){
return $('#' + id).val();
}

Unable to add options to the select dynamically from json

i have this select, with id category and product. If a choose one option in the select category, the other should list all products in that category.
var json = JSON.parse(xhr.responseText);
console.log('value: '+e.value);
for(var x in json) {
console.log(x+' -> id: '+json[x]['id']);
var all = document.getElementById(target).querySelector("#all");
document.getElementById(target).innerHTML = '';
document.getElementById(target).appendChild(all);
var data = json[x];
if(e.value == '*') {
console.log('add ('+data['id']+', '+data['nome']+')');
var child = document.createElement("option");
child.setAttribute("value", data['id']);
child.innerText = data['nome'];
document.getElementById(target).appendChild(child);
} else {
if(data['categoria'].id == e.value) {
console.log('add ('+data['id']+', '+data['nome']+')');
var child = document.createElement("option");
child.setAttribute("value", data['id']);
child.innerText = data['nome'];
document.getElementById(target).appendChild(child);
}
}
}
<div class="row">
<div class="col-sm">
Category:
<select class="form-control" id="category" data-target="product" th:attr="data-url=#{/produto/listBy.json}" onchange="fill_produtos(this);">
<option value="*">All</option>
<option th:each="option : ${categories}" th:value="${option.id}">
<span th:each="t : ${option.nome}" th:if="${#strings.equals(#strings.substringBefore(t.idioma,','), #strings.replace(#locale,'_','-'))}" th:href="#{/categoria/__${t.conteudo}__}" th:text="${t.conteudo}"></span>
</option>
</select>
</div>
<div class="col-sm">
Produto:
<select class="form-control" id="product">
<option id="all" value="*">All</option>
<option th:each="option : ${produtos}" th:value="${option.id}" th:text="${option.nome}"></option>
</select>
</div>
<div class="col-sm">
Date Range: <input type="date" class="form-control"> a <input type="date" class="form-control">
</div>
</div>
Right now, this is not happening as expected. I have this 3 categories (named one, two and three), each one with 1 product (prod1, prod2 and prod3). I select categories one or two, no products are listed on the other select; if I select category three or all, only the product three are listed on the other select.
Except that the debug code (the console.log) added to the function seems to follow the right path when I click each option on category: if I click one, only the message inside the if(data['categoria'].id == e.value) is shown; same for two and three. If click all, all messages are shown, as expected, due the instruction telling to do so after if(e.value == '*').
Anyone can see what I am doing wrong here? I know I am missing something, but I can't see what is.

Select box I need it to default to first option after click on submit

I'm using a select box with a list of option that gets populated from a google sheet that all works fine but what i need is for the select box to go back to the first option after I click submit. Here is my select box code:
<script type="text/javascript"></script>
<script>
<?
var sheet = SpreadsheetApp.openById("1GerAhvhytiKKrOUCTiavDuPRJAT9uYYRje2d85ED3").getSheetByName("Data");
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("B2:B"+lastRow);
var data = myRange.getValues();
?>
</script>
<div class="row">
<div class="input-field col s4 l4">
<i class="material-icons prefix">person</i>
<select id="Emp" >
<option value="" disabled selected>Select your name</option> <!--THIS IS THE OPTION I NEED AFTER SUBMIT-->
<? for (var i = 0; i < data.length; ++i) { ?>
<option ><?!= data[i] ?></option>
<? } ?>
</select>
</div>
When I click on submit I have a script that clear all the value and goes back to the top of the form but i can't seem to get this select box to go back to the first option that says Select your name. I've tried adding this to my script that clear the other field but it's not working
document.getElementById("Emp").selectedIndex = 0;

Categories

Resources