Read and write excel using javascript and hta - javascript

Here is the code to read the data from the excel sheet and paste that data into html table. It shows an error,when i convert the data from html table to excel sheet,but at the sametime this coding is working in vbscript,not working in javascript what is the solution for that..
<html>
<head>
<HTA:application
Applicationname="MyApp"
BORDER="dialog"
BORDERSTYLE="complex"
Caption="yes"
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
VERSION="2.0"
WINDOWSTATE="maximize"/>
<title>Read Excel</title>
<style type="text/css">
body
{
background-color:White;
}
P
{
font:bold 18px arial;
}
</style>
<script language="javascript" type="text/javascript">
var rowCount,colCount,selectexcel,objExcel,tempcol,intRow,intCol;
var rowData;
var mySpan;
var textData;
function ReadExcelData()
{
selectexcel = prompt("Please enter the file path", "D:\VBScriptTrainee\Sample.xlsx");
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = false;
objExcel.Workbooks.Open(selectexcel);
rowCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
colCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Columns.Count
alert(rowCount);
alert(colCount);
//colCount=colCount+1;
tempcol=colCount;
rowData="<table border=2>";
for (intRow=1;intRow <= rowCount;intRow++)
{
rowData = rowData + "<tr>";
for (intCol=1;intCol <= colCount;intCol++)
{
if ((intRow != 1) && (intCol ==tempcol))
{
rowData = rowData + "<td>" + "<input type='checkbox' id='flag_id' name='flag' />" + "</td>";
}
else if (intRow ==1)
{
rowData = rowData + "<td>" + objExcel.Cells(intRow,intCol).Value + "</td>";
}
else
{
rowData= rowData + "<td><div contentEditable='True'>" + objExcel.Cells(intRow,intCol).Value + "</div></td>";
}
}
rowData = rowData + "</tr>";
}
rowData =rowData + "</table>";
//document.write(rowData);
mySpan = document.getElementById('Span_id_two');
mySpan.innerHTML = rowData + "<br>";
//objExcel = undefined;
}
function WriteExcelData()
{
//mwresult = Msgbox ("Are you Sure to Write ?",vbOKCancel)
//var objExcelTwo;
//objExcelTwo = new ActiveXObject("Excel.Application");
//objExcelTwo.Visible = true;
//objExcelTwo.Workbooks.Open(selectexcel);
var tableValue;
var mySpan=document.getElementById('Span_id_two');
textData=mySpan.innerHTML;
var tab=document.getElementsByTagName("table")(0);
var mytable = document.getElementsByTagName("table")(0).rows.length;
//document.write(mytable);
var mytable1= document.getElementsByTagName("table")(0).rows(0).cells.length;
//document.write(mytable1);
for(n = 0;n<=(mytable-1);n++)
{
for(j = 0;j<=(mytable1-1);j++)
{
objExcel.Cells(n+1,j+1).Value = tab.Rows(n).Cells(j).innerHTML;
tableValue = tab.Rows(n).Cells(j).innerHTML;
if(tableValue == "<INPUT id=flag_id type=checkbox CHECKED name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="Yes";
}
if(tableValue == "<INPUT id=flag_id type=checkbox name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="No";
}
}
}
//var find ="<*>";
//var rplace =" ";
//objExcel.Cells.Replace find,rplace;
//MsgBox "Data Exported Successfully",vbInformation
//objExcel.ActiveWorkbook.Save;
//Set objExcel=nothing
}
</script>
</head>
<body>
<center>
<img src="Excel.png" height=200 width=300/>
</center>
<center>
<h1 align="center" style="color:blue"><img src="icon-developer-icon.png" height=100px width=100px/>
Read Excel (Row by Row)</h1><br>
<input type="button" name="Read" value="Click To Read" onclick="ReadExcelData()"/>
<input type="button" name="Write" value="Click To Write" onclick="WriteExcelData()"/>
</center>
<br>
<br>
<div>
<center>
<!--<table border="2px" color="Red">
<th id="thead"></th>
<tr>
<td>-->
<br>
<!--<div class="jumbotron">-->
<span ID="Span_id_two" Style="Color:blue;" name="text_name">
</span>
<br>
<!--</td>
</tr>
</table>-->
<marquee direction="Right" style="Color:red;">**Note : Select only excel files**</marquee>
</center>
</div>
</div>
</div>
</div>
</body>
</html>
It shows the following error 'object doesn't support this property or method'
in WriteExcelData function.

Related

Want to convert my google script web app into custom menu pop up

I made a google sheet script web app but I want to create a custom menu from where I can get my web app as pop up on the same page so that I don't need to always go to web app link or if any alternative you know please help me...
I want to make a searching operation which we can use inside our sheet or by making something in a new sheet also where we can get all the data inside the sheet.
this is a scripting file
Code. gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
function processForm(formObject){
var result = "";
if(formObject.searchtext){
result = search(formObject.searchtext);
}
return result;
}
function search(searchtext){
var spreadsheetId = '1JZanz4UZObZeLfN-z1RM77VcS_13pEBVcxf4pLzZ7wY';
var dataRage = 'APAC!A3:P';
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
var ar = [];
data.forEach(f=> {
if (~f.indexOf(searchtext)) {
ar.push(f);
}
});
return ar;
}
This is an HTML file
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!--##JAVASCRIPT FUNCTIONS ---------------------------------------------------- -->
<script>
//PREVENT FORMS FROM SUBMITTING / PREVENT DEFAULT BEHAVIOUR
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, true);
//HANDLE FORM SUBMISSION
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(createTable).processForm(formObject);
document.getElementById("search-form").reset();
}
//CREATE THE DATA TABLE
function createTable(dataArray) {
if(dataArray && dataArray !== undefined && dataArray.length != 0){
var result = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+
"<th scope='col'>Manage status</th>"+
"<th scope='col'>Site Code</th>"+
"<th scope='col'>BU</th>"+
"<th scope='col'>Site name</th>"+
"<th scope='col'>SSH / Telnet</th>"+
"<th scope='col'>Comment</th>"+
"<th scope='col'>Hostname</th>"+
"<th scope='col'>Model</th>"+
"<th scope='col'>Function</th>"+
"<th scope='col'>AAA config</th>"+
"<th scope='col'>Mgt IP</th>"+
"<th scope='col'>Subnet</th>"+
"<th scope='col'>VLAN</th>"+
"<th scope='col'>Location</th>"+
"<th scope='col'>Serial No </th>"+
"<th scope='col'>Software Ver </th>"+
"</tr>"+
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('search-results');
div.innerHTML = result;
}else{
var div = document.getElementById('search-results');
//div.empty()
div.innerHTML = "Data not found!";
}
}
</script>
<!--##JAVASCRIPT FUNCTIONS ~ END ---------------------------------------------------- -->
</head>
<style>
th,td{
border-left:1px dashed gray;
}
</style>
<body>
<div class="container">
<br>
<div class="row">
<div class="col">
<!-- ## SEARCH FORM ------------------------------------------------ -->
<form id="search-form" class="form-inline" onsubmit="handleFormSubmit(this)">
<div class="form-group mb-2">
<label for="searchtext">Search Text</label>
</div>
<div class="form-group mx-sm-3 mb-2">
<input type="text" class="form-control" id="searchtext" name="searchtext" placeholder="Search Text">
</div>
<button type="submit" class="btn btn-primary mb-2">Search</button>
</form>
<!-- ## SEARCH FORM ~ END ------------------------------------------- -->
</div>
</div>
<div class="row">
<div class="col">
<!-- ## TABLE OF SEARCH RESULTS ------------------------------------------------ -->
<div id="search-results" class="table-responsive">
<!-- The Data Table is inserted here by JavaScript -->
</div>
<!-- ## TABLE OF SEARCH RESULTS ~ END ------------------------------------------------ -->
</div>
</div>
</div>
</body>
</html>
Try:
function launchwebapdialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createTemplateFromFile('Index').evaluate(),'Title');
}
I got this to work. No it's not the same. But you can take it to the next step from here.
gs:
function processForm(formObject){
Logger.log(JSON.stringify(formObject));
var result = "";
if(formObject.searchtext){
result = search(formObject.searchtext);
}
return result;
}
function search(searchtext){
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const tf = sh.createTextFinder(searchtext).findAll();
let found=tf.map(e => e.getA1Notation());
return found;
}
function launchwebapdialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createTemplateFromFile('ah1').evaluate(),'Title');
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function handleFormSubmit(formObject) {
google.script.run
.withSuccessHandler(createTable)
.processForm(formObject);
}
function createTable(dataArray) {
document.getElementById("search-form").reset();
document.getElementById('search-results').innerHTML = dataArray.join(', ');
}
</script>
</head>
<body>
<div class="container">
<br>
<div class="row">
<div class="col">
<form id="search-form" class="form-inline">
<div class="form-group mb-2">
<label for="searchtext">Search Text</label>
</div>
<div class="form-group mx-sm-3 mb-2">
<input type="text" class="form-control" id="searchtext" name="searchtext" placeholder="Search Text">
</div>
<input type="button" value="Search" onclick="handleFormSubmit(this.parentNode);" />
</form>
</div>
</div>
<div class="row">
<div class="col">
<div id="search-results" class="table-responsive">
</div>
</div>
</div>
</div>
</body>
</html>

How do i make the headings of table align to the content?

I am a beginner to appscript. I am developing a payment system where user can see their payment history and can pay their payment. But for now after I have made some changes to my code, after that the content and headings wont get aligned together, so Im now seeking for some help from you guys. I have included the link to my appscript and some images to explain my self better. Thank you so much
Code.gs
var url = "https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006";
var streetSheetName = "JALAN SANGGUL 4";
function doGet(e) {
var streetSheetName = "JALAN SANGGUL 4"; // Added
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
return HtmlService.createHtmlOutputFromFile('WebAppLogin')
.setTitle("Resident Payment");
}
function checkLogin(username, password) {
var found_record = '';
var name = '';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("USERNAMES");
var getLastRow = webAppSheet.getLastRow();
for(var i = 2; i <= getLastRow; i++) {
if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == username.toUpperCase() && webAppSheet.getRange(i, 7).getValue() == password) {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
} else if (username.toUpperCase() == 'ADMIN' && password == 'ADMINPASSWORD') {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
}
}
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
if(found_record == '') {
found_record = 'FALSE';
}
return [found_record, username,name];
}
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 changePassword(username, newPassword) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("USERNAMES");
var range = sheet.getRange("A2:A").createTextFinder(username).matchEntireCell(true).findNext();
if (range) {
range.offset(0, 6).setValue(newPassword);
}
}
function GetUsernameAssociatedProperties(username) {
var filteredDataRangeValues = '';
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName("USERNAMES");
var dataRangeValues = displaySheet.getDataRange().getValues();
if (username.toUpperCase() == 'ADMIN') {
dataRangeValues.shift();
filteredDataRangeValues = dataRangeValues;
} else {
filteredDataRangeValues = dataRangeValues.filter(row => row[0].toUpperCase() == username.toUpperCase());
}
return filteredDataRangeValues;
}
function GetPaymentRecords(userProperties,filter) {
var streetSheetName = PropertiesService.getScriptProperties().getProperty("streetSheetName"); // Added
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(1, 7, displaySheet.getLastRow(), displaySheet.getLastColumn() - 6).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;
}
WebAppLogin.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").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("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("errorMessage").innerHTML = "";
document.getElementById("currentUser").value = name; // CHANGE
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;
google.script.run.withSuccessHandler(displayTable).GetRecords(username, filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
ar = ar.sort((a, b) => new Date(a).getTime() > new Date(b).getTime() ? -1 : 1).splice(-12); // <--- Added
var name = document.getElementById("currentUser").value; // CHANGE
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">Select the Year</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option>';
filterString.filter(String).forEach(str => {
filter += '<option value="'+str+'">'+str+'</option>';
});
filter += '</select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
}
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
if (!ar.some(([a,,,d]) => {
var t = new Date(a);
return year == t.getFullYear() && month == t.getMonth() && d.toUpperCase() == "PAID";
})) {
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 = '';
}
//change the link according to ur webapp latest version
function LogOut(){
window.open("https://script.google.com/macros/s/AKfycbwKa4sQ441WUIqmU40laBP0mfiqNMiN-NghEvwUnJY/dev",'_top');
}
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
</script>
</head>
<body>
<style>
h2 {text-align: center;}
div {text-align: center;}
.col-centered{margin: 0 auto;float: none;}
</style>
<h2> Resident Payment Status Portal</h2>
</div>
<div id="loginDisplay" style="padding: 10px">
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>User Name</label>
<input type="text" id="username" class="form-control" required/>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>Password</label><br>
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<hr>
<button class="btn btn-primary" type="button" id="LoginButton" onclick="GetRecords()" >
Login
</button>
<span id="errorMessage" style="color: red" ></span>
</div>
<hr>
<div style="display:none" id="dataDisplay">
<div>
<h2 id="firstLastName"></h2>
</div>
<input type="hidden" id="currentUser" value=""/>
<div style="width:1200px;margin:0 auto;">
<div id ="myFilter" class="form-group"></div>
<hr>
<div id="displayRecords" style="padding: 10px;" ></div>
<!----Paypal Button-------->
<hr>
<div style="width:500px;margin:0 auto;">
<div id="digitalgoods-030521182921-1" style="display: none;"></div>
<script>(function (div, currency) {var item_total = {currency_code: currency,value: '50.00',},tax_total = {currency_code: currency,value: '0.00' },render = function () {window.paypal.Buttons({createOrder: function (data, actions) {return actions.order.create({application_context: {brand_name: "",landing_page: "BILLING",shipping_preference: "NO_SHIPPING",payment_method: {payee_preferred: "UNRESTRICTED"}},purchase_units: [{description: "",soft_descriptor: "digitalgoods",amount: {breakdown: {item_total: item_total,tax_total: tax_total},value: '50.00' },items: [{name: "Monthly Fees",quantity: 1,description: "",sku: "1",unit_amount: item_total,tax: tax_total}]}]});},onApprove: function (data, actions) {return actions.order.capture().then(function (details) {div.innerHTML = "Order completed. You\x27ll receive an email shortly!";});},onCancel: function (data) {},onError: function (err) {div.innerHTML = "<pre>" + err.toString()}}).render("#digitalgoods-030521182921-1");},init = function () {window.digitalgoods = window.digitalgoods || [];window.digitalgoods.push(render);var file = "https://www.paypal.com/sdk/js?client-id=AS-86gVX_DfakSkq6YZDJRdKZb4SMIziOd5c9DIKy4extQrpb0VFEprDleB_duKI4BJQQRewUdfliZEf\x26currency=MYR";var script = document.createElement("script");script.type = "text/javascript";script.src = file;script.onload = function() {var i = window.digitalgoods.length;while (i--) {window.digitalgoods[i]();}};div.appendChild(script);};init();})(document.getElementById("digitalgoods-030521182921-1"), "MYR");</script>
</div>
<!-----Change Password----------->
<div>
<!--<button type="button" class="btn btn-primary btn-md" onclick="changePassword()">Change Password</button>-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Change Password
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLongTitle">Change Password</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter New Password</label><br>
<input type="password" id="newPassword" class="form-control" required/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="changePassword()">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<hr>
<!-----Log Out----------->
<div>
<button type="button" class="btn btn-default btn-md" onclick="LogOut()">
<span class="glyphicon glyphicon-log-out"></span> Log out
</button>
</div>
</div>
</body>
</html>
Can you put this code in WebAppLogin.html
<!DOCTYPE html>
<html>
<head>
</style>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").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("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("errorMessage").innerHTML = "";
document.getElementById("currentUser").value = name; // CHANGE
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;
google.script.run.withSuccessHandler(displayTable).GetRecords(username, filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
ar = ar.sort((a, b) => new Date(a).getTime() > new Date(b).getTime() ? -1 : 1).splice(-12); // <--- Added
var name = document.getElementById("currentUser").value; // CHANGE
if(ar.length > 0) {
var displayTable = '<table class=\"table\" id=\"mainTable\">';
displayTable += "<tr>";
displayTable += '<th style=\"text-align: center;\">Month</th>';
displayTable += '<th style=\"text-align: center;\">House Number</th>';
displayTable += '<th style=\"text-align: center;\">Street</th>';
displayTable += '<th style=\"text-align: center;\">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">Select the Year</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option>';
filterString.filter(String).forEach(str => {
filter += '<option value="'+str+'">'+str+'</option>';
});
filter += '</select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
}
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
if (!ar.some(([a,,,d]) => {
var t = new Date(a);
return year == t.getFullYear() && month == t.getMonth() && d.toUpperCase() == "PAID";
})) {
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 = '';
}
//change the link according to ur webapp latest version
function LogOut(){
window.open("https://script.google.com/macros/s/AKfycbwKa4sQ441WUIqmU40laBP0mfiqNMiN-NghEvwUnJY/dev",'_top');
}
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
</script>
</head>
<body>
<style>
h2 {text-align: center;}
div {text-align: center;}
.col-centered{margin: 0 auto;float: none;}
</style>
<h2> Resident Payment Status Portal</h2>
</div>
<div id="loginDisplay" style="padding: 10px">
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>User Name</label>
<input type="text" id="username" class="form-control" required/>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>Password</label><br>
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<hr>
<button class="btn btn-primary" type="button" id="LoginButton" onclick="GetRecords()" >
Login
</button>
<span id="errorMessage" style="color: red" ></span>
</div>
<hr>
<div style="display:none" id="dataDisplay">
<div>
<h2 id="firstLastName"></h2>
</div>
<input type="hidden" id="currentUser" value=""/>
<div style="width:1200px;margin:0 auto;">
<div id ="myFilter" class="form-group"></div>
<hr>
<div id="displayRecords" style="padding: 10px;" ></div>
<!----Paypal Button-------->
<hr>
<div style="width:500px;margin:0 auto;">
<div id="digitalgoods-030521182921-1" style="display: none;"></div>
<script>(function (div, currency) {var item_total = {currency_code: currency,value: '50.00',},tax_total = {currency_code: currency,value: '0.00' },render = function () {window.paypal.Buttons({createOrder: function (data, actions) {return actions.order.create({application_context: {brand_name: "",landing_page: "BILLING",shipping_preference: "NO_SHIPPING",payment_method: {payee_preferred: "UNRESTRICTED"}},purchase_units: [{description: "",soft_descriptor: "digitalgoods",amount: {breakdown: {item_total: item_total,tax_total: tax_total},value: '50.00' },items: [{name: "Monthly Fees",quantity: 1,description: "",sku: "1",unit_amount: item_total,tax: tax_total}]}]});},onApprove: function (data, actions) {return actions.order.capture().then(function (details) {div.innerHTML = "Order completed. You\x27ll receive an email shortly!";});},onCancel: function (data) {},onError: function (err) {div.innerHTML = "<pre>" + err.toString()}}).render("#digitalgoods-030521182921-1");},init = function () {window.digitalgoods = window.digitalgoods || [];window.digitalgoods.push(render);var file = "https://www.paypal.com/sdk/js?client-id=AS-86gVX_DfakSkq6YZDJRdKZb4SMIziOd5c9DIKy4extQrpb0VFEprDleB_duKI4BJQQRewUdfliZEf\x26currency=MYR";var script = document.createElement("script");script.type = "text/javascript";script.src = file;script.onload = function() {var i = window.digitalgoods.length;while (i--) {window.digitalgoods[i]();}};div.appendChild(script);};init();})(document.getElementById("digitalgoods-030521182921-1"), "MYR");</script>
</div>
<!-----Change Password----------->
<div>
<!--<button type="button" class="btn btn-primary btn-md" onclick="changePassword()">Change Password</button>-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Change Password
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLongTitle">Change Password</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter New Password</label><br>
<input type="password" id="newPassword" class="form-control" required/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="changePassword()">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<hr>
<!-----Log Out----------->
<div>
<button type="button" class="btn btn-default btn-md" onclick="LogOut()">
<span class="glyphicon glyphicon-log-out"></span> Log out
</button>
</div>
</div>
</body>
</html>
Happy to help.
Thanks.

Submit Button Not Changing Questions

I am building a cute webpage for my teacher (who's very fun) as a Christmas present, but whenever I enter text into the input box and submit any question past the first, the code marks it as incorrect. I thought I had fixed this problem when I changed the question submit, every time the question changes, but apparently not. Can someone tell me what I'm doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Funn Chunn | Quiz</title>
<link rel="icon" href="images/alabama logo.png"/>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body onload="firstQ();">
<div class='container'>
<div class='row'>
<h1 id='mainHeader'>Funn Chunn | Quiz</h1>
</div>
<div class='row'>
<h3 id='questionBox'></h3>
</div>
<div class='row'>
<form id="inputBoxOuter">
<input id='inputBox' type='text'></br>
<button class='btn btn-lg btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>
</form>
</div>
<div class='row'>
<form id="playAgainOuter">
</form>
</div>
<div class="row">
<p id="subText"></p>
</div>
<div class="row">
<div id="logoImgOuter"><img class="mx-auto" id="logoImg" src="images/alabama logo.png"/></div>
</div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
JavaScript
var mainHeaderJs = document.getElementById("mainHeader");
var questionBoxJs = document.getElementById("questionBox");
var inputBoxJs = document.getElementById("inputBox");
var inputBoxOuterJs = document.getElementById("inputBoxOuter");
var subTextJs = document.getElementById("subText");
var logoImgOuterJs = document.getElementById("logoImgOuter");
var playAgainOuter = document.getElementById("playAgainOuter");
var playerScore = 0;
function finalScore() {
mainHeaderJs.innerHTML = "You Got a Score of " + playerScore + " Out of 10";
playAgainOuter.innerHTML = "<button class='btn btn-lg btn-info mx-auto' id='playAgain' onclick='playAgain();'>Play Again</button>"
questionBoxJs.innerHTML = "";
inputBoxOuterJs.innerHTML = "";
}
function playAgain() {
mainHeaderJs.innerHTML = "Funn Chunn | Quiz";
firstQ();
playerScore = 0;
playAgainOuter.innerHTML = "";
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>";
}
function moveOnGood() {
subTextJs.innerHTML = "Correct! Moving on to the next question";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function moveOnBad() {
subTextJs.innerHTML = "Moving on to the next question...";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function firstQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 1: What is Mrs. Chunn's Favorite Team?";
}, 2000);
}
function firstQAnswer() {
var Q1Answer = inputBoxJs.value;
Q1Answer = Q1Answer.toUpperCase();
if (Q1Answer == "ALABAMA") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON TIDE") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
moveOnBad();
secondQ();
}
}
function secondQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 2: Is Mrs. Chunn a Millenial?";
}, 2000);
}
function secondQAnswer() {
var Q2Answer = inputBoxJs.value;
Q2Answer = Q2Answer.toUpperCase();
if (Q2Answer == "YES") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "YEAH") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "Y") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswerAlt();'>Enter</button>";
moveOnBad();
thirdQ();
}
}
This isn't the best solution, but its one that should work. Just initialize inputBoxjs = ''; and update inputBoxjs at the start of every question function.
So change
var inputBoxJs = document.getElementById("inputBox");
to
var inputBoxJs = '';
and add this line
inputBoxJs = document.getElementById("inputBox");
above your Q1Answer and Q2Answer variables.
Then just add your thirdQ function and variables after you're finished with your Q2 functions.
Hopefully this helps.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Funn Chunn | Quiz</title>
<link rel="icon" href="images/alabama logo.png"/>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body onload="firstQ();">
<div class='container'>
<div class='row'>
<h1 id='mainHeader'>Funn Chunn | Quiz</h1>
</div>
<div class='row'>
<h3 id='questionBox'></h3>
</div>
<div class='row'>
<form id="inputBoxOuter">
<input id='inputBox' type='text'> <br/>
<button class='btn btn-lg btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>
</form>
</div>
<div class='row'>
<form id="playAgainOuter">
</form>
</div>
<div class="row">
<p id="subText"></p>
</div>
<div class="row">
<div id="logoImgOuter"><img class="mx-auto" id="logoImg" src="images/alabama logo.png"/></div>
</div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
<script>
var mainHeaderJs = document.getElementById("mainHeader");
var questionBoxJs = document.getElementById("questionBox");
var inputBoxJs = '';
var inputBoxOuterJs = document.getElementById("inputBoxOuter");
var subTextJs = document.getElementById("subText");
var logoImgOuterJs = document.getElementById("logoImgOuter");
var playAgainOuter = document.getElementById("playAgainOuter");
var playerScore = 0;
function finalScore() {
mainHeaderJs.innerHTML = "You Got a Score of " + playerScore + " Out of 10";
playAgainOuter.innerHTML = "<button class='btn btn-lg btn-info mx-auto' id='playAgain' onclick='playAgain();'>Play Again</button>"
questionBoxJs.innerHTML = "";
inputBoxOuterJs.innerHTML = "";
}
function playAgain() {
mainHeaderJs.innerHTML = "Funn Chunn | Quiz";
firstQ();
playerScore = 0;
playAgainOuter.innerHTML = "";
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>";
}
function moveOnGood() {
subTextJs.innerHTML = "Correct! Moving on to the next question";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function moveOnBad() {
subTextJs.innerHTML = "Moving on to the next question...";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function firstQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 1: What is Mrs. Chunn's Favorite Team?";
}, 2000);
}
function firstQAnswer() {
inputBoxJs = document.getElementById("inputBox");
var Q1Answer = inputBoxJs.value;
Q1Answer = Q1Answer.toUpperCase();
if (Q1Answer == "ALABAMA") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON TIDE") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
moveOnBad();
secondQ();
}
}
function secondQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 2: Is Mrs. Chunn a Millenial?";
}, 2000);
}
function secondQAnswer() {
inputBoxJs = document.getElementById("inputBox");
var Q2Answer = inputBoxJs.value;
Q2Answer = Q2Answer.toUpperCase();
if (Q2Answer == "YES") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "YEAH") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "Y") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswerAlt();'>Enter</button>";
moveOnBad();
thirdQ();
}
}
</script>

How to implement checkValidity() in forms?

I don't know why checkValidity() method is not checking if my input is true or false. My program said that checkValidity() is not a function... My program was working but the checkValidity() debug my program.
I tried to make a program that adds data in tables and checks that the input is valid or invalid. Every time you click the process button, data gets added to a table and the reset will erase the input and clears the table.
My professor familiarize me in using the checkValidity() method to ensure the input is valid. I don't know if my program has an error or the browser does not support the checkValidity method?
I use latest version of Chrome. Can Everyone check my code if there's an error and teach me how to implement checkValidity method?
<!DOCTYPE html>
<html lang="en">
<head><title>Sales Person</title>
<!-- Latest compiled CSS -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Optional theme -->
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4">
<form name="myform" onsubmit="validateForm return false;">
<div class="row">
<div class="form-group">
<label for="name">Sales Person:</label>
<input type="text" id = "name" placeholder="Enter Your Name" required><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 1:</label>
<input type="number" id = "product1" placeholder="Enter Product 1"><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 2:</label>
<input type="number" id = "product2" placeholder="Enter Product 2" ><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 3:</label>
<input type="number" id = "product3" placeholder="Enter Product 3" ><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 4:</label>
<input type="number" id = "product4" placeholder="Enter Product 4" ><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 5:</label>
<input type="number" id = "product5" placeholder="Enter Product 5" ><br/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<input type="submit" class="btn btn-default" onclick="Process()" value="Submit">
</div>
<div class="col-md-3">
<input type="reset" class="btn btn-default" onclick="erase()" value="Reset">
</div>
</form>
</div>
<div class="col-md-8" id="sales_table">
</div>
</div>
</div>
<script>
"use strict";
var table = "";
var table_header = "";
var table_body = "";
var table_footer = "";
table_header += "<table class= table table-bordered>";
table_header += "<tr>";
table_header += "<th class='text-center'>Name</th>";
table_header += "<th class='text-center'>Product 1</th>";
table_header += "<th class='text-center'>Product 2</th>";
table_header += "<th class='text-center'>Product 3</th>";
table_header += "<th class='text-center'>Product 4</th>";
table_header += "<th class='text-center'>Product 5</th>";
table_header += "<th class='text-center'>Total Sale Product</th>";
table_header += "<th class='text-center'>Commissions</th>";
table_header += "<tr>";
table_footer += "</table>";
function Process()
{
var sales_table = document.getElementById("sales_table").value;
var name=document.getElementById("name").value;
var product1=parseInt(document.getElementById("product1").value);
var product2=parseInt(document.getElementById("product2").value);
var product3=parseInt(document.getElementById("product3").value);
var product4=parseInt(document.getElementById("product4").value);
var product5=parseInt(document.getElementById("product5").value);
var sales_table = document.getElementById("sales_table");
var total;
var commissions;
if(isValid(name,product1,product2,product3,product4,product5)){
total = product1+product2+product3+product4+product5;
commissions = total * .30;
table_body += "<tr>";
table_body += "<td>"+name+"</td>";
table_body += "<td class='text-center'>" + product1.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product2.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product3.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product4.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product5.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + total.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + commissions.toFixed(2) + "</td>";
table_body += "</tr>";
table = table_header + table_body + table_footer;
sales_table.innerHTML = table;
}
}
function isValid (name,product1,product2,product3,product4,product5) {
try{
if(name.checkValidity==false){
throw name.validationMessage
}
if(product1.checkValidity==false){
throw product1.validationMessage
}
if(product2.checkValidity==false){
throw product2.validationMessage
}
if(product3.checkValidity==false){
throw product3.validationMessage
}
if(product4.checkValidity==false){
throw product4.validationMessage
}
if(product5.checkValidity==false){
throw product5.validationMessage
}
}
catch(err){
alert(err);
return false;
}
return true;
}
function erase()
{
document.getElementById("name").value="";
document.getElementById("product1").value="";
document.getElementById("product2").value="";
document.getElementById("product3").value="";
document.getElementById("product4").value="";
document.getElementById("product5").value="";
document.getElementById("sales_table").innerHTML="";
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
It looks like checkValidity is a method added in the HTML5 specification for input fields: Constraints validation.
You need to keep the reference of the input element, not the value itself:
var name=document.getElementById("name");
var product1=document.getElementById("product1");
var product2=document.getElementById("product2");
var product3=document.getElementById("product3");
var product4=document.getElementById("product4");
var product5=document.getElementById("product5");
Then, you can invoke the checkValidity method later on in your isValid function ;)
if (!name.checkValidity()) {
throw name.validationMessage;
}
// etc.
And you need to adapt the content of your if statement:
total = parseInt(product1.value) + parseInt(product2.value) + parseInt(product3.value) + parseInt(product4.value) + parseInt(product5.value);
commissions = total * .30;
table_body += "<tr>";
table_body += "<td>"+name.value+"</td>";
table_body += "<td class='text-center'>" + parseInt(product1.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product2.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product3.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product4.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product5.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + total.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + commissions.toFixed(2) + "</td>";
table_body += "</tr>";
checkValidity is a method.
Normaly you call methods with () at the end like> method().
e.g. for product3 product3.checkValidity()==false

Toggle hide/show table td in .hta

I've seen several of posts regarding this subject, but I have not managed to solve my own problem despite of having tried different methods.
I am programming in a .hta file, where I have all my notes titles listed above each other. Whenever you click a note title the description should appear (toggle/expand) under the title. All the notes should start hidden.
sub searchdata
SQL_query = "SELECT * FROM dvd WHERE Title LIKE '%"& txtsrch.value &"%' OR Notes LIKE '%"& txtsrch.value &"%' ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML2 = strHTML2 & ""
Do Until rsData.EOF = True
strHTML2 = strHTML2 & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><span class'togglelink'><td width='70%' style='cursor: pointer'><b>" & rsData("Title") & "</b></td></span><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><span class='toggle' style='display: block'><td colspan='2'>" & rsData("Notes") & "</td></span></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML2 = strHTML2 & ""
searchIT.innerHTML = strHTML2
end sub
I am using this JS script to run it:
<script type="text/javascript">
$(document).ready(function () {
$('.toggle').hide();
$('span.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('fast');
elem.toggle('fast');
});
});
</script>
I can easily get the script to work when testing with just plain text.
JSFiddle
Side question: Is programming in a HTA really so different from HTML? I'm running in to a lot of problems trying to convert my whole site (MySQL, PHP, HTML) to working in HTA.
Thanks in advance!
Update: Listed my whole .hta script:
<html>
<HTA:APPLICATION ID="oHTA"
APPLICATIONNAME="myApp"
BORDER="thick"
CAPTION="yes"
ICON=./images/Icon.ico
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
RESIZE="yes"
VERSION=7.2
WINDOWSTATE="normal"
contextMenu=no
>
<head>
<style>
#vis1{
display:none;
}
</style>
<script type="text/javascript"> // Width and height in pixel to the window
window.resizeTo(683,725);
</script>
<script type="text/javascript">
var enablepersist="on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="Yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}
function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}
function expandcontent(cid){
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}
function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}
function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}
document.cookie=window.location.pathname+"="+selectedItem
}
function do_onload(){
uniqueidn=window.location.pathname+"firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined"){
document.cookie=(get_cookie(uniqueidn)=="")? uniqueidn+"=1" : uniqueidn+"=0"
firsttimeload=(get_cookie(uniqueidn)==1)? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload
if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate
</script>
<title>Søgning</title>
<link href="stylesheet/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="SHORTCUT ICON" href="images/icon.ico"/>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.7.min.js"></script>
<script language="vbscript">
Dim conn 'GLOBAL doing this here so that all functions can use it
sub dotheconnection
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =./Database/data.mdb; User Id=; Password="
If conn.errors.count <> 0 Then
else
' if connected OK call sub getdata
getdata
end if
end sub
sub getdata
SQL_query = "SELECT * FROM dvd ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML = strHTML & ""
Do Until rsData.EOF = True
strHTML = strHTML & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><td width='70%' style='cursor: pointer'><span id='vis'><b>" & rsData("Title") & "</b></span></td><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><td colspan='2'><span id='vis1'>" & rsData("Notes") & "</span></td></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML = strHTML & ""
SQL_query = "SELECT Count(*) AS intTotal FROM dvd"
Set rsData = conn.Execute(SQL_query)
strHTML1 = strHTML1 & ""
strHTML1 = strHTML1 & "" & rsData("intTotal") & " "
Count.innerHTML = strHTML1
end sub
sub searchdata
SQL_query = "SELECT * FROM dvd WHERE Title LIKE '%"& txtsrch.value &"%' OR Notes LIKE '%"& txtsrch.value &"%' ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML2 = strHTML2 & ""
Do Until rsData.EOF = True
strHTML2 = strHTML2 & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><span class'togglelink'><td width='70%' style='cursor: pointer'><b>" & rsData("Title") & "</b></td></span><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><span class='toggle' style='display: block'><td colspan='2'>" & rsData("Notes") & "</td></span></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML2 = strHTML2 & ""
searchIT.innerHTML = strHTML2
end sub
sub deleteUser(id)
If MsgBox("Vil du slettet dette notat?", vbYesNo) =vbYes Then
SQL_query = "DELETE * FROM dvd WHERE ID = " & id
conn.Execute(SQL_query)
getdata
reloadpage()
Else
MsgBox("Notatet er ikke blevet slettet.")
End IF
end sub
sub addUser
SQL_query = "INSERT INTO dvd (Title,Length,Notes,Cat) VALUES ('"& txtTitle.value &"','"& txtLength.value &"','"& txtNotes.value &"','"& txtCat.value &"')"
conn.Execute(SQL_query)
reloadpage()
expandcontent("sc2")
getdata
end sub
sub editUser(id)
SQL_query = "SELECT * FROM dvd WHERE ID=" & id
Set rsData=conn.Execute(SQL_query)
txtTitle.value = rsData("Title")
txtLength.value = rsData("Length")
txtNotes.value = rsData("Notes")
txtCat.value = rsData("Cat")
txtID.value = rsData("ID")
btnUpdate.disabled = false // Show
btnOpret.disabled = true // Hide
expandcontent("sc2")
getdata
end sub
sub updateUser
SQL_query = "UPDATE dvd SET Title='"& txtTitle.value &"', Length='"& txtLength.value &"' , Notes='"& txtNotes.value &"', Cat='"& txtCat.value &"' WHERE ID= " & txtID.value
conn.Execute(SQL_query)
getdata
reloadpage()
expandcontent("sc2")
end sub
</script>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.7.min.js"></script>
<SCRIPT TYPE="text/javascript">
function init()
{
dotheconnection();
searchdata();
getdata();
}
</SCRIPT>
<script>
function addNotat() {
btnOpret.disabled = false; // Show
btnUpdate.disabled = true; // Hide
expandcontent("sc2");
}
</script>
<script>
function reloadpage() {
location.reload();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.toggle').hide();
$('div.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('fast');
elem.toggle('fast');
});
});
</script>
</head>
<body onLoad="init()" language="vbscript">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="40" width="20%" id="top_bar">
<input language="vbscript" onload="searchdata" onkeyup="searchdata" name="txtsrch" id="filter_input" width="15%" tabindex="0" autofocus="autofocus" size="35" type="search" style="background: url(images/search_bg.png) #FFF no-repeat left; padding-left: 20px; margin-left: 10px" placeholder="Søgning"> </td>
<td id="top_bar"></div><span id="Count"></span> notater </td>
<td width="22%" id="top_bar" align="right"><input type="button" style="margin-right: 10px" onClick="history.go(0)" value="Opdater"><a onClick="addNotat()" style="cursor: hand">Opret</a> </span></td>
<td width="20%" id="top_bar" align="right"><img src="images/footer-logo.png" style="margin-right: 10px" border="0" title="Gå til forsiden" /></td>
</tr>
</table>
<br>
<div id="sc2" class="switchcontent" style="margin-left: 10px">
<b>Title:<br></b><input type="text" name="txtTitle" size="43"><br>
<b>Kategori:</b><br>
<select size="1" name="txtCat">
<option value="">Vælg kategori</option>
<option value="Thriller">Thriller</option>
<option value="Westerns">Westerns</option>
</select><br>
<b>Length</b><br><input type="text" name="txtLength" size="8"><br>
<b>Notat:</b><br><textarea rows="6" name="txtNotes" cols="55"></textarea><br>
<p align="left"><b>
<input type="button" name="btnOpret" value="Opret" onclick="addUser" language="vbscript" disabled>
<input type="button" name="btnUpdate" value="Gem" onclick="updateUser" language="vbscript" disabled>
<input type="hidden" name="txtID">
</b></p>
</div>
</div>
<div id="searchIT" style="margin-left: 10px"></div>
</body>
</script>
</html>
The div.togglelink's will be attached after the document has been loaded, your on-handler will only have an effect to elements that are present when the document loads.
Attach the handler to the body instead:
$('body').on('click','span.togglelink',function(){/*your callback*/});

Categories