Google Web App Dynamic Dependent Dropdown - google-apps-script

I've been trying to add 3rd and 4th level dependent dropdown using the code from Code with Curt(https://codewithcurt.com/create-dependent-drop-down-on-google-web-app/), but I'm running into some issues. In this code below, I'm trying to add a 3rd level, but it doesn't seem to work. This is the output I'm trying to achieve. I'm not sure if there's a fastest way to load the dropdown from Google sheets, as this codes loads in about 3 seconds, or a better way to fetch it from Sheets.
Here's the code:
Google Apps Script:
function doGet(e) {
var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
var colors = getColors();
htmlOutput.message = '';
htmlOutput.colors = colors;
return htmlOutput.evaluate();
}
function doPost(e) {
Logger.log(JSON.stringify(e));
var name = e.parameters.name.toString();
var color = e.parameters.color.toString();
var fruit = e.parameters.fruit.toString();
var class = e.parameters.class.toString(); //class is a reserved word
AddRecord(name, color, fruit, class);
var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
var colors = getColors();
htmlOutput.message = 'Record Added';
htmlOutput.colors = colors;
return htmlOutput.evaluate();
}
function getColors() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for (var i = 2; i <= getLastRow; i++) {
if (return_array.indexOf(lovSheet.getRange(i, 1).getValue()) === -1) {
return_array.push(lovSheet.getRange(i, 1).getValue());
}
}
return return_array;
}
function getFruits(color) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for (var i = 2; i <= getLastRow; i++) {
if (lovSheet.getRange(i, 1).getValue() === color) {
return_array.push(lovSheet.getRange(i, 2).getValue());
}
}
return return_array;
}
function getClass(fruit) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for (var i = 2; i <= getLastRow; i++) {
if (lovSheet.getRange(i, 2).getValue() === fruit) {
return_array.push(lovSheet.getRange(i, 3).getValue());
}
}
return return_array.sort();
}
function AddRecord(name, color, fruit, class) {
var url = ''; //URL OF GOOGLE SHEET;
var ss = SpreadsheetApp.openByUrl(url);
var dataSheet = ss.getSheetByName("DATA");
dataSheet.appendRow([name, color, fruit, class, new Date()]);
}
function getUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function GetFruit(color)
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
fruit.length = 0;
let option = document.createElement("option");
option.value = "";
option.text = "";
fruit.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
option.value = item;
option.text = item;
fruit.appendChild(option);
});
}).getFruits(color);
};
function getClass(queue)
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
class.length = 0;
let option = document.createElement("option");
option.value = "";
option.text = "";
class.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
option.value = item;
option.text = item;
class.appendChild(option);
});
}).getClass(queue);
};
</script>
<h1>Web App Dependent Drop Down</h1>
<?var url = getUrl();?>
<form method="post" action="<?= url ?>">
<label style="font-size: 20px" >Name</label><br>
<input type="text" name="name" style="font-size: 20px" /><br><br>
<label style="font-size: 20px" >Colors</label><br>
<select name="color" style="font-size: 20px" onchange="GetFruit(this.value)" >
<option value="" ></option>
<? for(var i = 0; i < colors.length; i++) { ?>
<option value="<?= colors[i] ?>" ><?= colors[i] ?></option>
<? } ?>
</select><br><br>
<label style="font-size: 20px" >Fruit</label><br>
<select name="fruit" id="fruit" style="font-size: 20px" >
</select><br><br>
<label style="font-size: 20px" >Class</label><br>
<select name="location" id="location" style="font-size: 20px" >
<option value="" selected disabled>Select Class</option>
</select><br><br>
<label style="font-size: 20px" >Brand</label><br>
<select name="location" id="location" style="font-size: 20px" >
<option value="" selected disabled>Select Brand</option>
</select><br><br>
<input type="submit" name="submitButton" value="Submit" style="font-size: 20px" />
<span style="font-size: 20px" ><?= message ?></span>
</form>
</body>
</html>

I believe your goal is as follows.
You want to reduce the process cost of your script.
Modification points:
When a loop process is used using the HTML template, the process cost becomes high. Ref
In this case, the HTML template is used for replacing the values.
When google.script.run is used, the process cost becomes high.
In this case, google.script.run is used for sending the values to the Google Apps Script side instead of the form submission.
From your showing script, I thought that the values might not be required to be sent with the HTML request. So, in this modification, the values are sent with google.script.run.
Creations of the options in the select tag are done in Javascript using the 1st loaded values.
In your Google Apps Script side, getValue() is used in a loop. In this case, the process cost becomes high. Ref
When these points are reflected in your showing script, how about the following modification?
Google Apps Script side:
function doGet(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOV");
var [, ...values] = sheet.getDataRange().getDisplayValues();
var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
htmlOutput.values = JSON.stringify(values);
htmlOutput.message = '';
return htmlOutput.evaluate();
}
function addRecord({ name, color, fruit, clas, brand }) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA");
sheet.appendRow([name, color, fruit, clas, brand, new Date()]);
}
HTML & Javascript side:
<h1>Web App Dependent Drop Down</h1>
<form>
<label style="font-size: 20px" >Name</label><br>
<input type="text" name="name" style="font-size: 20px" /><br><br>
<label style="font-size: 20px" >Colors</label><br>
<select id="colors" name="color" style="font-size: 20px" onchange="setOptions('fruit', getValues(this.value, 0))" ></select><br><br>
<label style="font-size: 20px" >Fruit</label><br>
<select name="fruit" id="fruit" style="font-size: 20px" onchange="setOptions('clas', getValues(this.value, 1))" ></select><br><br>
<label style="font-size: 20px" >Class</label><br>
<select name="clas" id="clas" style="font-size: 20px" onchange="setOptions('brand', getValues(this.value, 2))" ></select><br><br>
<label style="font-size: 20px" >Brand</label><br>
<select name="brand" id="brand" style="font-size: 20px" ></select><br><br>
<input type="button" name="submitButton" value="Submit" style="font-size: 20px" onclick="sample(this.parentNode)" >
<span style="font-size: 20px" ><?= message ?></span>
</form>
<script>
const values = JSON.parse(<?= values ?>);
function setOptions(id, v) {
const s = document.getElementById(id);
s.innerHTML = "";
v.forEach(a => {
const option = document.createElement("option");
option.value = a;
option.innerHTML = a;
s.appendChild(option);
});
}
function getValues(e, i) {
return ["", ...new Set(values.reduce((ar, r) => (r[i] == e && ar.push(r[i + 1]), ar), []))];
}
window.onload = function() {
setOptions("colors", ["", ...new Set(values.map(([a]) => a))]);
}
function sample(e) {
google.script.run.addRecord(e);
}
</script>
Note:
When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in the report "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

You may use the following GAS and HTML:
Google Apps Script
I have added the onlyUnique function (from another SO post) to filter out similar entries. I also added other functions to cater the Class and Brand columns. I also changed the variable class to classParam since class is a reserved word.
function doGet(e) {
var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
var colors = getColors();
var fruits = getFruits();
var classParams = getClasses();
var brands = getBrands();
htmlOutput.message = '';
htmlOutput.colors = colors;
htmlOutput.fruits = fruits;
htmlOutput.classParams = classParams;
htmlOutput.brands = brands;
return htmlOutput.evaluate();
}
function doPost(e) {
Logger.log(JSON.stringify(e));
var name = e.parameters.name.toString();
var color = e.parameters.color.toString();
var fruit = e.parameters.fruit.toString();
var classParam = e.parameters.classParam.toString();
var brand = e.parameters.brand.toString();
AddRecord(name, color, fruit, classParam, brand);
var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
var colors = getColors();
var fruits = getFruits();
var classParams = getClasses();
var brands = getBrands();
htmlOutput.message = 'Record Added';
htmlOutput.colors = colors;
htmlOutput.fruits = fruits;
htmlOutput.classParams = classParams;
htmlOutput.brands = brands;
return htmlOutput.evaluate();
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function getColors() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if(return_array.indexOf(lovSheet.getRange(i, 1).getValue()) === -1) {
return_array.push(lovSheet.getRange(i, 1).getValue());
}
}
return return_array.filter(onlyUnique);
}
function getFruits(color) {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if(lovSheet.getRange(i, 1).getValue() === color) {
return_array.push(lovSheet.getRange(i, 2).getValue());
}
}
return return_array.filter(onlyUnique);
}
function getClasses(color, fruit) {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if((lovSheet.getRange(i, 1).getValue() === color) && (lovSheet.getRange(i, 2).getValue() === fruit)) {
return_array.push(lovSheet.getRange(i, 3).getValue());
}
}
return return_array.filter(onlyUnique);
}
function getBrands(color, fruit, classParam) {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var lovSheet = ss.getSheetByName("LOV");
var getLastRow = lovSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if((lovSheet.getRange(i, 1).getValue() === color) && (lovSheet.getRange(i, 2).getValue() === fruit) && (lovSheet.getRange(i, 3).getValue() === classParam)) {
return_array.push(lovSheet.getRange(i, 4).getValue());
}
}
return return_array.filter(onlyUnique);
}
function AddRecord(name, color, fruit, classParam, brand) {
var url = ""; //INSERT SPREADSHEET URL HERE <---------
var ss = SpreadsheetApp.openByUrl(url);
var dataSheet = ss.getSheetByName("DATA");
dataSheet.appendRow([name, color, fruit, classParam, brand, new Date()]);
}
function getUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function GetFruit(color)
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
fruit.length = 0;
let option = document.createElement("option");
option.value = "";
option.text = "";
fruit.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
option.value = item;
option.text = item;
fruit.appendChild(option);
});
}).getFruits(color);
};
function GetClass(color, fruit)
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
classParam.length = 0;
let option = document.createElement("option");
option.value = "";
option.text = "";
classParam.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
option.value = item;
option.text = item;
classParam.appendChild(option);
});
}).getClasses(color, fruit);
};
function GetBrand(color, fruit, classParam)
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
brand.length = 0;
let option = document.createElement("option");
option.value = "";
option.text = "";
brand.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
option.value = item;
option.text = item;
brand.appendChild(option);
});
}).getBrands(color, fruit, classParam);
};
</script>
</head>
<body>
<h1>Web App Dependent Drop Down</h1>
<?var url = getUrl();?>
<form method="post" action="<?= url ?>" >
<!-- name -->
<label style="font-size: 20px" >Name</label><br>
<input type="text" name="name" style="font-size: 20px" /><br><br>
<!-- color -->
<label style="font-size: 20px" >Colors</label><br>
<select name="color" id="color" style="font-size: 20px" onchange="GetFruit(this.value)" >
<option value="" ></option>
<? for(var i = 0; i < colors.length; i++) { ?>
<option value="<?= colors[i] ?>" ><?= colors[i] ?></option>
<? } ?>
</select><br><br>
<!-- fruit -->
<label style="font-size: 20px" >Fruits</label><br>
<select name="fruit" id="fruit" style="font-size: 20px" onchange="GetClass(color.value, this.value)" >
<option value="" ></option>
<? for(var i = 0; i < fruits.length; i++) { ?>
<option value="<?= fruits[i] ?>" ><?= fruits[i] ?></option>
<? } ?>
</select><br><br>
<!-- class -->
<label style="font-size: 20px" >Classes</label><br>
<select name="classParam" id="classParam" style="font-size: 20px" onchange="GetBrand(color.value, fruit.value, this.value)" >
<option value="" ></option>
<? for(var i = 0; i < classParams.length; i++) { ?>
<option value="<?= classParams[i] ?>" ><?= classParams[i] ?></option>
<? } ?>
</select><br><br>
<!-- brand -->
<label style="font-size: 20px" >Brand</label><br>
<select name="brand" id="brand" style="font-size: 20px" >
</select><br><br>
<input type="submit" name="submitButton" value="Submit" style="font-size: 20px" />
<span style="font-size: 20px" ><?= message ?></span>
</form>
</body>
</html>
Sample Data
Web App
Output

Related

Grouping the tables with dropdown box

I am a beginner in google app script. So right now I am doing a project where users can sign in and can view their payment history. So for now it is just showing from 2020 until 2021. So I want your guys help on creating a dropdown box which states (eg : 2020 , 2021 ) so maybe if the user clicks 2020 then they can see the payment history of 2020 only. I really need your guys help in this thing. I have attached the link to my google app script and a image to explain myself better. Thank you guys.
https://script.google.com/d/1DdRKqUX__-ZITUgTZanQ_A7hUL1kcc0TZOeFmn58wYsX_o_7cqNExnYo/edit?usp=sharing - Link to my appscript
First image
Second Image
Here is a sample code you can refer with:
WebAppLogin.html (modifications)
<script>
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
console.log(output);
var username = output[1];
var name = output[2];
if(output[0] == 'TRUE') {
document.getElementById("errorMessage").innerHTML = "";
document.getElementById("currentUser").value = username;
google.script.run.withSuccessHandler(displayTable).GetRecords(username,"None");
} else if(output[0] == 'FALSE') {
document.getElementById("firstLastName").innerHTML = "";
document.getElementById("currentUser").value = "";
document.getElementById("myFilter").innerHTML = "";
document.getElementById("errorMessage").innerHTML = "Failed to Login";
document.getElementById("LoginButton").innerHTML = "Login";
}
}).checkLogin(username, password);
}
function filter(){
var filterStr = document.getElementById("filterYear").value;
var user = document.getElementById("currentUser").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(user,filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
var username = document.getElementById("currentUser").value;
if(ar.length > 0) {
var displayTable = '<table class=\"table\" id=\"mainTable\" >';
displayTable += "<tr>";
displayTable += "<th>Month</th>";
displayTable += "<th>House Number</th>";
displayTable += "<th>Street</th>";
displayTable += "<th>Payment Status</th>";
displayTable += "</tr>";
ar.forEach(function(item, index) {
displayTable += "<tr>";
displayTable += "<td>"+item[0]+"</td>";
displayTable += "<td>"+item[1]+"</td>";
displayTable += "<td>"+item[2]+"</td>";
displayTable += "<td>"+item[3]+"</td>";
displayTable += "</tr>";
});
displayTable += "</table>";
} else {
var displayTable = "<span style=\"font-weight: bold\" >No Records Found</span>";
}
var filter = '';
if(filterString.length > 0) {
filter += '<label for="years" style="font-size: 20px">Years</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option>';
filterString.forEach(str => {
filter += '<option value="'+str+'">'+str+'</option>';
});
filter += '</select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
}
//var filter = '<label for="years" style="font-size: 20px">Years</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option><option value="2020">2020</option><option value="2021">2021</option></select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
document.getElementById("digitalgoods-030521182921-1").style.display = "block";
document.getElementById("displayRecords").innerHTML = displayTable;
document.getElementById("firstLastName").innerHTML = "USER: " + name;
document.getElementById("myFilter").innerHTML = filter;
document.getElementById("LoginButton").innerHTML = "Login";
document.getElementById("username").value = '';
document.getElementById("password").value = '';
}
</script>
<div>
<h2 id="firstLastName">
</h2>
</div>
<input type="hidden" id="currentUser" value=""/>
<div id ="myFilter" class="form-group">
</div>
</div>
<div id="displayRecords" style="padding: 10px;" >
</div>
Modifications done:
Include empty form-group class
Include hidden input to hold current logged-in user
Create a reusable function displayTable()
Create an html content for the drop-down filter. See variable filter.
Include another argument when calling GetRecords(username, filter)
Create a new function filter()
During initial log-in, filter will be set to "None". filter will be set depending on the option selected
Code.gs (modifications)
function GetRecords(username,filter) {
var filteredDataRangeValues = GetUsernameAssociatedProperties(username);
var resultArray = GetPaymentRecords(filteredDataRangeValues,filter);
var resultFilter = getYears();
result = {
data: resultArray,
filter: resultFilter
};
return result;
}
function getYears() {
var ss= SpreadsheetApp.openByUrl(url);
var yearSheet = ss.getSheetByName("Configuration");
var getLastRow = yearSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if(return_array.indexOf(yearSheet.getRange(i, 2).getDisplayValue()) === -1) {
return_array.push(yearSheet.getRange(i, 2).getDisplayValue());
}
}
return return_array;
}
function GetPaymentRecords(userProperties,filter) {
var transpose = m => m[0].map((_, i) => m.map(x => x[i]));
var resultArray = [];
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName(streetSheetName);
var addressValues = displaySheet.getRange("B:C").getValues();
var paidMonthValues = displaySheet.getRange("G:AD").getValues();
//Logger.log(addressValues);
//Logger.log(transpose(paidMonthValues));
userProperties.forEach((v, i) => {
var userHouseNumber = v[1];
var userStreet = v[2];
var column = addressValues.reduce(function callbackFn(accumulator, currentValue, index, array) {
if (currentValue[0] == userHouseNumber && currentValue[1] == userStreet) {
return index
} else {
return accumulator
}
}, '');
//Logger.log(column);
Logger.log(filter)
Logger.log(paidMonthValues);
if(filter=="None"){
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}else{
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
if(element[0].includes(filter))return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}
resultArray = resultArray.concat(result);
//Logger.log(resultArray);
})
//Remove null elements
resultArray = resultArray.filter(element=>{
Logger.log(element!=null)
return element != null;
});
return resultArray;
}
Modifications done:
Modified GetRecords() and GetPaymentRecords() to include filter option
Add removal of null elements in the resultArray. (Null elements may exist when filter option was used due to the map() used)
Output:
(After user logged-in)
(After user selects a filter)
(UPDATE):
The following modifications where done to create a drop-box based on the list of years available in the configuration sheet.
WebAppLogin.html
displayTable() was modified that will accept an object as its parameter which contains an array data and an array of filter strings.
displayTable() was modified to update the drop-down options based on the filter strings available
Code.gs
getYears() was added that will read the sheet "Configuration" to get the filter string values
GetRecords() was modified to return an object which contains an array of record data and an array of filter strings.

show selected option value info to other select tag [duplicate]

i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<select class="select" id="city" disabled>
<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>
this one is not visible, and acts as a container for all the elements filtered out by the selection:
<span id="option-container" style="visibility: hidden; position:absolute;"></span>
Finally, the script that filters:
<script>
function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip
It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle.
//Get html elements
var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
Fiddle Demo
I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
</script>
</head>
<body>1
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Japn</option>
<option>Shuidong</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
</body>
</html>
This is an example that I've done. I wish that will be useful for you.
$(document).ready(function(){
var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);
function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {
if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}
$("#cycles").change(function(){
remplirListNiveau(this.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>

Add fields to this html form who add/edit data in a spreadsheet

I found the scripts below on this post, and I tried to figure out how to add a new column on the sheet and make it work with the html form the same way as the two columns already existing
But without success...
If someone can take the time to explain to me how to do it, it would be very nice 🙏
The HTML /CSS side and basic JS are understandable for me but the rest stay hard to understand by myself
Here the sheet sample
Thanks !
CODE.GS
function doGet(request) {
return HtmlService.createTemplateFromFile('Form').evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* Find ID*/
function getID(IDsearch){
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
/*set cells to plain text*/
var range = ws.getRange(1, 1, ws.getMaxRows(), ws.getMaxColumns());
range.setNumberFormat("#");
var data = ws.getRange(3, 1, ws.getLastRow(), 2).getValues();
var dataInput = data.map(function(r){return r[1];}); //ID column
var position = dataInput.indexOf(IDsearch); //index of the row where ID is
Logger.log(position);
var dataArray = ws.getRange(position+3, 1, 1, 2).getValues(); //array with data from searched ID
var clientsDataString = dataArray.toString();
var clientsDataArray = clientsDataString.split(',');
if(position > -1){
return clientsDataArray;
} else {
return position;
}
}
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
var ranges = ws.getRange(4, 2, ws.getLastRow() - 3, 1).createTextFinder(formObject.ID).findAll();
if (ranges.length > 0) {
for (var i = 0; i < ranges.length; i++) {
ranges[i].offset(0, -1, 1, 2).setValues([[formObject.name, formObject.ID]]);
}
} else {
ws.appendRow([formObject.name, formObject.ID]);
}
}
JavaScript.html
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
/* Search for ID */
document.getElementById("btn-procurar").addEventListener("click", onSearch);
function onSearch() {
var IDsearch = document.getElementById("insertID").value;
google.script.run.withSuccessHandler(populateForm).getID(IDsearch);
}
function populateForm(clientsData) {
document.getElementById("name").value = clientsData[0];
document.getElementById("ID").value = clientsData[1];
}
</script>
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/Contact-Form-Clean.css">
<link rel="stylesheet" href="/styles.css">
<?!= include('JavaScript'); ?>
<?!= include('form-css'); ?>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="register-photo" style="padding-top: 30px;">
<div class="form-container" style="width: 695px;">
<form id="myForm" onsubmit="handleFormSubmit(this)" method="post" style="width: 720px;padding: 10px;padding-right: 20px;padding-left: 25px;">
<input class="form-control" type="text" id="name" name="name" placeholder="Name" style="width: 300px;display: inline-block;margin-bottom: 20px;">
<input class="form-control" type="number" id="ID" name="ID" placeholder="ID" style="width: 165px;display: inline-block;" required="">
<button type="submit" id="btn-submeter" onclick="return confirm('Submit?')" class="btn btn-primary btn-block" style="width: 644px;margin-bottom: 35px;">Save data</button>
<script>
document.getElementById("myForm").addEventListener("submit", myFunction);
function myFunction() {
alert("Success");
}
</script>
<div id="output"></div>
<div style="margin-bottom: 15px;padding: 5px;background-color: rgba(255,255,255,0);padding-top: 0px;border-top: double;">
<h6 class="text-left" style="margin-top: 15px;display: inline-block;width: 519px;margin-right: 20px;margin-bottom: 10px;">Search/Fetch ID</h6>
<input class="form-control" type="text" id="insertID" name="insertID" placeholder="Insert ID" style="width: 155px;display: inline-block;">
<button class="btn btn-primary" id="btn-procurar" onclick="onSearch()" type="button" style="width: 450px;margin: 10px 0px 25px 0px;padding: 6px;margin-top: 0px;margin-bottom: 0px;margin-left: 29px;">Search by ID</button>
</div>
</form>
</div>
</div>
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
You want to put the values of "name", "ID", "address", "email" and "phone" using the HTML form.
In your updated shared Spreadsheet, 5 input tags are put.
You want to achieve this by modifying your script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your current script, 2 values are used like [formObject.name, formObject.ID].
For this, please modify to 5 values like [formObject.name, formObject.ID, formObject.address, formObject.email, formObject.phone].
modified script
When your script is modified, it becomes as follows.
From:
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
var ranges = ws.getRange(4, 2, ws.getLastRow() - 3, 1).createTextFinder(formObject.ID).findAll();
if (ranges.length > 0) {
for (var i = 0; i < ranges.length; i++) {
ranges[i].offset(0, -1, 1, 2).setValues([[formObject.name, formObject.ID]]);
}
} else {
ws.appendRow([formObject.name, formObject.ID]);
}
}
To:
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
var ranges = ws.getRange(4, 2, ws.getLastRow() - 3, 1).createTextFinder(formObject.ID).findAll();
var v = [formObject.name, formObject.ID, formObject.address, formObject.email, formObject.phone]; // Added
if (ranges.length > 0) {
for (var i = 0; i < ranges.length; i++) {
ranges[i].offset(0, -1, 1, v.length).setValues([v]); // Modified
}
} else {
ws.appendRow(v); // Modified
}
}
Note:
In your updated shared Spreadsheet, type="number" is used for the input tag of phone. In this case, for example, when the value is 01 33 33 33 33 33, an error occurs because 01 33 33 33 33 33 is not the number. If you want to show 01 33 33 33 33 33, please modify to type="string".

Countdown timer start/stop/reset button with Apps Script to Google Sheets

I have some issues about countdown timer with start/stop/reset command button on Google Sheets . how to write a script for it by using google apps script, and put in google sheets, command by using start/stop/reset button.
A Javascript Timer for Gathering data off of a Spreadsheet
I built this as a test setup for one of my projects. Here's the datatimer.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
#my_block{border:2px solid black;background-color:rgba(0,150,255,0.2);padding:10px 10px 10px 10px;}
#conv_block{border: 1px solid black;padding:10px 10px 10px 10px;}
.bttn_block{padding:5px 5px 0px 0px;}
.sndr_block {border:1px solid rgba(0,150,0,0.5);background-color:rgba(150,150,0,0.2);margin-bottom:2px;}
</style>
</head>
<body>
<form>
<div id="my_block" class="block form-group">
<div class="sndr_block">
<div id="myClock"></div>
<br />Timer Duration(minutes):
<br /><input id="txt1" type="text" size="4" class="action"/>
<select id="sel1" onChange="loadTxt('sel1','txt1');">
<option value="90000">1.5</option>
<option value="96000">1.6</option>
<option value="102000">1.7</option>
<option value="108000">1.8</option>
<option value="114000">1.9</option>
<option value="120000" selected>2.0</option>
<option value="126000">2.1</option>
<option value="132000">2.2</option>
<option value="138000">2.3</option>
<option value="144000">2.4</option>
</select>
<div id="cntdiv"></div>
<br /><strong>Timer Controls</strong>
<div class="bttn_block"><input type="button" value="Start" name="startShow" id="startShow" onClick="startmytimer();" class="red" /></div>
<div class="bttn_block"><input type="button" value="Stop" name="stopTimer" id="stopTimer" class="red" /></div>
<div class="bttn_block"><input type="button" value="Single Ping" name="changedata" id="chgData" class="red" onClick="changeData();" /></div>
</div>
<div id="btn-bar">
<br /><input type="button" value="Exit" onClick="google.script.host.close();" class="green" />
</div>
</div>
</form>
<script>
var idx=1;
var myInterval='';
var cnt=0;
$(function() {
$('#startTimer').click(startmytimer);
$('#stopTimer').click(stopTimer);
$('#txt1').val('120000');
startTime();
});
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('myClock').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i){
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function startmytimer(){
document.getElementById('cntdiv').innerHTML='<strong>Timer Started:</strong> ' + document.getElementById('myClock').innerHTML;
myInterval=setInterval(changeData, Number($('#txt1').val()));
}
function stopTimer(){
document.getElementById('cntdiv').innerHTML='Timer Stopped';
clearInterval(myInterval);
}
function loadTxt(from,to){
document.getElementById(to).value = document.getElementById(from).value;
}
function changeData(){
$('#txt1').css('background','#ffffcc');
google.script.run
.withSuccessHandler(updateDisplay)
.changeData();
}
function updateDisplay(t){
$('#txt1').css('background','#ffffff');
document.getElementById('cntdiv').innerHTML='<strong>Timer Running:</strong> Count= ' + ++cnt + ' <strong>Time:</strong> ' + t;
}
console.log('My Code');
</script>
</body>
</html>
Here's the datachanger.gs file:
function changeData(){
var ss=SpreadsheetApp.getActive();
var sho=ss.getSheetByName('TradingTimes')
var tmr=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "HH:mm:ss");
var col2=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd,yyyy HH:mm:ss");
var col3=new Date(col2).getTime();
var col4=new Date(col2).getTime();
var dA=[[col2,col3,col4]];
sho.getRange('B2:D2').setValues(dA);
return tmr;
}
function showTimerSideBar()
{
var ui=HtmlService.createHtmlOutputFromFile('datatimer').setTitle('Javascript Trigger Generator');
SpreadsheetApp.getUi().showSidebar(ui);
}
I was just watching the output from a sheet that had Google Finance cell functions in it. But you can call anything you want as often as you like.
Here's what the dialog looks like:
You can attach actions to images in a google sheet. That way you can have a start, stop and reset buttons as images. When clicked the images can link to functions in the appscript which updates the time in single cell.
Below is the code, and here is a sample sheet . See the "attach action to images" document on how to trigger the buttons if needed.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
function countDownSeconds(seconds, minutes){
while (minutes >=0){
sheet.getRange(2,1).setValue(minutes);
while (seconds >= 0 ){
var m = sheet.getRange(2,1).getValue()
var s = sheet.getRange(2,2).getValue()
if (m === 'pausing' || s === 'pausing'|| m === 'reset' || s === 'reset' ) {
return
}
sheet.getRange(2,2).setValue(seconds);
SpreadsheetApp.flush();
Utilities.sleep(1000)
seconds --
}
seconds = 59;
minutes = sheet.getRange(2,1).getValue();
minutes --
}
}
function startTimer(){
var minutes = sheet.getRange(2,1).getValue()
var seconds = sheet.getRange(2,2).getValue()
countDownSeconds(seconds, minutes)
}
function pause(){
var minutes = sheet.getRange(2,1).getValue()
var seconds = sheet.getRange(2,2).getValue()
sheet.getRange(2,1).setValue('pausing');
sheet.getRange(2,2).setValue('pausing');
SpreadsheetApp.flush();
Utilities.sleep(1000);
sheet.getRange(2,1).setValue(minutes)
sheet.getRange(2,2).setValue(seconds)
}
function reset(){
sheet.getRange(2,1).setValue('reset');
sheet.getRange(2,2).setValue('reset');
SpreadsheetApp.flush();
Utilities.sleep(1000);
sheet.getRange(2,1).setValue(0)
sheet.getRange(2,2).setValue(0)
}

How to make if I press the 'x' button, it will uncheck all that part and close it?

How to make if I press the 'x' button, it will uncheck all that part and close it? according to my coding, I only just managed to make the top but at the bottom it's not uncheck, and the checkbox at the bottom is not closed, I want it unchecked and closed the bottom checkbox.
Example at the 'solving' checkbox. When I tick that, there will be another checkbox. When I press 'x' button, it will uncheck the 'solving' checkbox. How to uncheck all of that at the bottom 'solving' checkbox and close it when I press 'x' button.
<header>
<h3><b><label for="search">Search</label></b>
<input id="search" type="text" name="search" placeholder="Search.." onkeyup="filterWithSearch(event)" /></h3>
<script>
function fungsi() {
var a = document.getElementById("subSolving1").checked;
var b = document.getElementById("subSolving2").checked;
var c = document.getElementById("subSolving3").checked;
var d = document.getElementById("subConclusion1").checked;
var e = document.getElementById("subConclusion2").checked;
var f = document.getElementById("subRepeated1").checked;
var g = document.getElementById("subRepeated2").checked;
console.log(a, b, c, d, e, f, g);
if (c || d === true) {
document.getElementById("Status").innerHTML = "Problem1";
} else if (b || a || e) {
document.getElementById("Status").innerHTML = "Problem2";
} else if (f && g) {
document.getElementById("Status").innerHTML = "Problem5";
} else if (f) {
document.getElementById("Status").innerHTML = "Problem3";
} else if (g) {
document.getElementById("Status").innerHTML = "Problem4";
}
}
function filterWithSearch(e) {
console.log(e)
if (e.which === 13) {
var searchStr = e.target.value.toLowerCase();
var cxb = document.getElementById('subOptionsContainer').querySelectorAll("label")
var subSolving = document.getElementById("subSolving");
var subConclusion = document.getElementById("subConclusion");
var subRepeated = document.getElementById("subRepeated");
if (searchStr === '') {
subSolving.style.display = Solving.checked ? "block" : "none";
subConclusion.style.display = Conclusion.checked ? "block" : "none";
subRepeated.style.display = Repeated.checked ? "block" : "none";
} else {
subSolving.style.display = "block";
subConclusion.style.display = "block";
subRepeated.style.display = "block";
}
for (var i = 0; i < cxb.length; i++) {
//console.log(cxb[i])
if (cxb[i].textContent.toLowerCase().indexOf(searchStr) !== -1) {
cxb[i].style.display = 'block';
} else {
cxb[i].style.display = 'none';
}
}
}
</script>
<body>
<b>Original:</b>
<div id="Alltry">
<script type="text/javascript">
function ShowHideDiv(Solving) {
var subSolving = document.getElementById("subSolving");
subSolving.style.display = Solving.checked ? "block" : "none";
var cxb = subSolving.getElementsByTagName('label');
for (var i = 0; i < cxb.length; i++) {
//console.log(cxb[i])
if (Solving.checked) {
cxb[i].style.display = 'block';
} else {
cxb[i].style.display = 'none';
}
}
}
function uncheckAll(divid) {
var checks = document.querySelectorAll('#' + divid + ' input[type="checkbox"]');
for (var i = 0; i < checks.length; i++) {
var check = checks[i];
if (!check.disabled) {
check.checked = false;
}
}
}
</script>
<div style="float: left; max-width: 80%;"><label for="Solving"> <input type="checkbox" id="Solving" onclick="ShowHideDiv(this)" value="Solving"/>Solving</label>
</div>
</div>
<script type="text/javascript">
function ShowHideDiv2(Conclusion) {
var subConclusion = document.getElementById("subConclusion");
subConclusion.style.display = Conclusion.checked ? "block" : "none";
}
</script>
<label for="Conclusion"> <input type="checkbox" id="Conclusion" onclick="ShowHideDiv2(this)" value="Conclusion"/>Conclusion</label>
<script type="text/javascript">
function ShowHideDiv3(Repeated) {
var subRepeated = document.getElementById("subRepeated");
subRepeated.style.display = Repeated.checked ? "block" : "none";
}
</script>
<label for="Repeated"> <input type="checkbox" id="Repeated" onclick="ShowHideDiv3(this)" value="Repeated"/>
Repeated</label>
<div id="subOptionsContainer">
<div id="subSolving" style="display: none">
<input type="button" id="uncheckAll" onclick="uncheckAll('Alltry')" value="x"><br>
<p><label> <input type="checkbox" id="subSolving1" onclick="fungsi()"/>subSolving1
</label></p>
<p><label> <input type="checkbox" id="subSolving2" onclick="fungsi()"/>subSolving2</label></p>
<p><label> <input type="checkbox" id="subSolving3" onclick="fungsi()"/>subSolving3 </label></p>
</div>
<div id="subConclusion" style="display: none">
<p><label> <input type="checkbox" id="subConclusion1" onclick="fungsi()"/>subConclusion</label></p>
<p><label> <input type="checkbox" id="subConclusion2" onclick="fungsi()"/>subConclusion
</label></p>
</div>
<div id="subRepeated" style="display: none">
<p><label> <input type="checkbox" id="subRepeated1" onclick="fungsi()"/>subRepeated1</label></p>
<p><label> <input type="checkbox" id="subRepeated2" onclick="fungsi()"/>subRepeated2
</label></p>
</div>
</div>
<b><hr/><p id="Status"></p></b></header>
</div>
</div>
just modify this function uncheckAll(divid) like below
function uncheckAll(divid) {
var checks = document.querySelectorAll('#' + divid + ' input[type="checkbox"]');
for (var i = 0; i < checks.length; i++) {
var check = checks[i];
if (!check.disabled) {
check.checked = false;
ShowHideDiv(Solving);
ShowHideDiv(Solving);
ShowHideDiv2(this);
ShowHideDiv3(this);
var Conclusion = document.getElementById("Conclusion").checked = false;
document.getElementById("Repeated").checked = false;
}
}
}
<header>
<h3><b><label for="search">Search</label></b>
<input id="search" type="text" name="search" placeholder="Search.." onkeyup="filterWithSearch(event)" /></h3>
<script>
function fungsi() {
var a = document.getElementById("subSolving1").checked;
var b = document.getElementById("subSolving2").checked;
var c = document.getElementById("subSolving3").checked;
var d = document.getElementById("subConclusion1").checked;
var e = document.getElementById("subConclusion2").checked;
var f = document.getElementById("subRepeated1").checked;
var g = document.getElementById("subRepeated2").checked;
console.log(a, b, c, d, e, f, g);
if (c || d === true) {
document.getElementById("Status").innerHTML = "Problem1";
} else if (b || a || e) {
document.getElementById("Status").innerHTML = "Problem2";
} else if (f && g) {
document.getElementById("Status").innerHTML = "Problem5";
} else if (f) {
document.getElementById("Status").innerHTML = "Problem3";
} else if (g) {
document.getElementById("Status").innerHTML = "Problem4";
}
}
function filterWithSearch(e) {
console.log(e)
if (e.which === 13) {
var searchStr = e.target.value.toLowerCase();
var cxb = document.getElementById('subOptionsContainer').querySelectorAll("label")
var subSolving = document.getElementById("subSolving");
var subConclusion = document.getElementById("subConclusion");
var subRepeated = document.getElementById("subRepeated");
if (searchStr === '') {
subSolving.style.display = Solving.checked ? "block" : "none";
subConclusion.style.display = Conclusion.checked ? "block" : "none";
subRepeated.style.display = Repeated.checked ? "block" : "none";
} else {
subSolving.style.display = "block";
subConclusion.style.display = "block";
subRepeated.style.display = "block";
}
for (var i = 0; i < cxb.length; i++) {
//console.log(cxb[i])
if (cxb[i].textContent.toLowerCase().indexOf(searchStr) !== -1) {
cxb[i].style.display = 'block';
} else {
cxb[i].style.display = 'none';
}
}
}
</script>
<body>
<b>Original:</b>
<div id="Alltry">
<script type="text/javascript">
function ShowHideDiv(Solving) {
var subSolving = document.getElementById("subSolving");
subSolving.style.display = Solving.checked ? "block" : "none";
var cxb = subSolving.getElementsByTagName('label');
for (var i = 0; i < cxb.length; i++) {
//console.log(cxb[i])
if (Solving.checked) {
cxb[i].style.display = 'block';
} else {
cxb[i].style.display = 'none';
}
}
}
function uncheckAll(divid) {
var checks = document.querySelectorAll('#' + divid + ' input[type="checkbox"]');
for (var i = 0; i < checks.length; i++) {
var check = checks[i];
if (!check.disabled) {
check.checked = false;
ShowHideDiv(Solving);
ShowHideDiv2(this);
ShowHideDiv3(this);
document.getElementById("Conclusion").checked = false;
document.getElementById("Repeated").checked = false;
document.getElementById("subSolving1").checked = false;
document.getElementById("subSolving2").checked = false;
document.getElementById("subSolving3").checked = false;
document.getElementById("subConclusion1").checked = false;
document.getElementById("subConclusion2").checked = false;
document.getElementById("subRepeated1").checked = false;
document.getElementById("subRepeated2").checked = false;
}
}
}
</script>
<div style="float: left; max-width: 80%;"><label for="Solving"> <input type="checkbox" id="Solving" onclick="ShowHideDiv(this)" value="Solving"/>Solving</label>
</div>
</div>
<script type="text/javascript">
function ShowHideDiv2(Conclusion) {
var subConclusion = document.getElementById("subConclusion");
subConclusion.style.display = Conclusion.checked ? "block" : "none";
}
</script>
<label for="Conclusion"> <input type="checkbox" id="Conclusion" onclick="ShowHideDiv2(this)" value="Conclusion"/>Conclusion</label>
<script type="text/javascript">
function ShowHideDiv3(Repeated) {
var subRepeated = document.getElementById("subRepeated");
subRepeated.style.display = Repeated.checked ? "block" : "none";
}
</script>
<label for="Repeated"> <input type="checkbox" id="Repeated" onclick="ShowHideDiv3(this)" value="Repeated"/>
Repeated</label>
<div id="subOptionsContainer">
<div id="subSolving" style="display: none">
<input type="button" id="uncheckAll" onclick="uncheckAll('Alltry')" value="x"><br>
<p><label> <input type="checkbox" id="subSolving1" onclick="fungsi()"/>subSolving1
</label></p>
<p><label> <input type="checkbox" id="subSolving2" onclick="fungsi()"/>subSolving2</label></p>
<p><label> <input type="checkbox" id="subSolving3" onclick="fungsi()"/>subSolving3 </label></p>
</div>
<div id="subConclusion" style="display: none">
<p><label> <input type="checkbox" id="subConclusion1" onclick="fungsi()"/>subConclusion</label></p>
<p><label> <input type="checkbox" id="subConclusion2" onclick="fungsi()"/>subConclusion
</label></p>
</div>
<div id="subRepeated" style="display: none">
<p><label> <input type="checkbox" id="subRepeated1" onclick="fungsi()"/>subRepeated1</label></p>
<p><label> <input type="checkbox" id="subRepeated2" onclick="fungsi()"/>subRepeated2
</label></p>
</div>
</div>
<b><hr/><p id="Status"></p></b></header>
</div>
</div>