Submit Button Not Changing Questions - javascript

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>

Related

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.

AJAX in 000webhost

I am having problem with AJAX in 000webhost. The output for AJAX is not displaying. Also, there is no error in the Console when I inspected.
This is my website link:
https://cwp-geoworld.000webhostapp.com/
The AJAX part is working fine with localhost and it can display the list of continents in the sidebar as well as a table in the middle of the page when the sidebar is clicked.
Example of how it should look like is here:
https://drive.google.com/open?id=1Tn5hQXepA--o4LTqBc_DzjeZ17yz830Z
Here are the codes for the index.php which contains the AJAX code:
<?php
include("control.php");
//require_once( "classes/session.class.php" );
$username = Session::getInstance()->getProperty("username");
$userRole = Session::getInstance()->getProperty("userRole");
require_once( "classes/PDOConnection.class.php" );
//header('Content-type: application/json');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>GeoWorld | Home</title>
<!--Icon at the tab-->
<link rel="icon" type="image/png" href="images/globe_icon.png"/>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="template/other_pages/bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="template/other_pages/bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="template/other_pages/bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="template/other_pages/dist/css/AdminLTE.min.css">
<!-- Skins -->
<link rel="stylesheet" href="template/other_pages/dist/css/skins/skin-purple.css">
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition skin-purple sidebar-mini">
<!--WRAPPER-->
<div class="wrapper">
<!-- Main Header -->
<header class='main-header'>
<!-- Logo -->
<a href='index.php' class='logo'>
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class='logo-mini'><i class='fa fa-globe'></i><b>Geo</b></span>
<!-- logo for regular state and mobile devices -->
<span class='logo-lg'><b>Geo</b>World</span>
</a>
<!-- Header Navbar -->
<nav class='navbar navbar-static-top' role='navigation'>
<!-- Sidebar toggle button-->
<a href='#' class='sidebar-toggle' data-toggle='push-menu' role='button'>
<span class='sr-only'>Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!--Include Conditions for Navbar-->
<?php include ('include/navbar.php'); ?>
</ul>
</div>
</nav>
</header>
<!--Include Sidebar-->
<?php include ('include/sidebar.php'); ?>
<!-- CONTENT WRAPPER -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1 align='center'>
Welcome to GeoWorld
</h1>
</section>
<!-- Main content -->
<section class="content container-fluid">
<!-- search form (Optional) -->
<div id="searchTextBox">
<div class="input-group">
<input type="text" id='search' name="search_country" maxlength=3 class="form-control" placeholder="Search for a country here...">
<span class="input-group-btn">
<button type="submit" id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</div><!-- /.search form -->
<br/>
<div class="searchResults"></div><br/>
<div class="box-body">
<div id="records"></div>
</div>
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
</div><!-- ./wrapper -->
<!-- Modal for show more details about country -->
<div class="modal fade" id="countryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">More details about the country</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<!-- Modal for show details about city -->
<div class="modal fade" id="cityModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">City details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<!-- Modal to update HOS -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<!-- Modal to upload flag -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Upload Flag</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
</body>
</html>
<!-- REQUIRED JS SCRIPTS -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<!-- jQuery 3 -->
<script src="template/other_pages/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="template/other_pages/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="template/other_pages/dist/js/adminlte.min.js"></script>
<!--script for displaying continents and countries records-->
<script type="text/javascript">
$(document).ready(function(){
//$('#searchTextBox').hide();
$('.records').hide();
$("input[name='search_country']").on('keypress', function (e) {
var charCode = e.which;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8)
return true;
else
return false;
});
});
$(function()
{
$.getJSON( "showAllContinents.php", function(obj)
{
$.each(obj, function(key, value)
{
var sidebarOption = "";
//sidebarOption = '<input type="hidden" value="showAllContinents" name="action"/>';
sidebarOption += '<li>';
sidebarOption += '<a data-id="'+value.ID+'" class="sidebar-country">';
sidebarOption += value.Name;
sidebarOption += '</a>';
sidebarOption += '</li>';
$(".treeview-menu").append(sidebarOption);
});
});//end of $.getJSON function
$("#options_continent").change(function() {
getCountryRecords($(this).val());
});//end of option function
$(document).on('click', '.sidebar-country', function() {
getCountryRecords($(this).attr('data-id'));
});
//to show LifeExpectancy, GNP and HOS when button is clicked
$("#records").on("click", "#tbl_countries button#more_details",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
//var result= $.parseJSON(data);
//console.log(result);
var string ='<table id="tbl_countries" class="table table-bordered table-hover"><tr><th>Life Expectancy</th><th>GNP</th><th>Head of State</th></tr>';
$.each( data, function( key, value )
{
$(".records").empty();
string += "<tr>"
+"<td>"+value['LifeExpectancy'] +"</td>"
+"<td>"+value['GNP']+"</td>"
+"<td>"+value['HeadOfState']+"</td>"
+"</tr>";
});
string += '</table>';
$(".modal-body").append(string);
} //end of function data
); //end of get
});//end of click button
//to show city details when button is clicked
$("#records").on("click", "#tbl_countries button#city_details",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCityDetails.php',
{A3Code: A3Code},
function(data)
{
var string ='<table id="tbl_countries" class="table table-bordered table-hover"><tr><th>City Name</th><th>District</th><th>Population</th><th>Latitude</th><th>Longitude</th></tr>';
$.each( data, function( key, value )
{
$(".records").empty();
string += "<tr>"
+"<td>"+value['name'] +"</td>"
+"<td>"+value['district']+"</td>"
+"<td>"+value['population']+"</td>"
+"<td>"+value['lat']+"</td>"
+"<td>"+value['lng']+"</td>"
+"</tr>";
});
string += '</table>';
//$(".records").append(string);
$(".modal-body").append(string);
} //end of function data
); //end of get
});//end of click button
//to update HOS modal box
$("#records").on("click", "button#update_HOS",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
var forms='';
$.each( data, function( key, value )
{
forms +='<form id="updateForm" name="updateForm" action="updateHOS.php" method="post">';
forms +='<div class="form-group">';
forms +='<input type="hidden" id="A3Code" name="A3Code" value='+value["A3Code"]+'>';
forms +='<label class="control-label">HOS:</label>';
forms +='<input type="text" class="form-control" id="hos" name="hos" value='+value['HeadOfState']+'>';
forms +='</div>';
forms += '<div class="form-group">';
forms += '<input type="submit" class="btn-success" id="updateBtn" name="updateBtn" value="Update">';
forms +='</div>';
forms +='</form>';
});
$(".modal-body").append(forms);
} //end of function data
); //end of get
});//end of click button */
//to show upload flag modal box
$("#records").on("click", "button#upload_flag",function()
{
$("#uploadModal .modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
var uploadForm='';
$.each( data, function( key, value )
{
uploadForm +='<form id="uploadFlagForm" name="uploadFlagForm" action="upload_flag.php" method="post" enctype="multipart/form-data">';
uploadForm +='<div class="form-group" align="center">';
uploadForm +='<input type="hidden" id="A3Code" name="A3Code" value='+value["A3Code"]+'>';
uploadForm +='<input type="file" name="fileToUpload" id="fileToUpload">';
uploadForm +='</div>';
uploadForm += '<div class="form-group" align="center">';
uploadForm += '<button type="submit" class="btn btn-primary" id="uploadBtn" name="uploadBtn">Upload Flag</button>';
uploadForm +='</div>';
uploadForm +='</form>';
});
$("#uploadModal .modal-body").append(uploadForm);
} //end of function data
); //end of get
});//end of click button
//To get country records
function getCountryRecords(id) {
$.ajax
({
url: 'showCountryInfo.php',
type: 'post',
data: {ID:id},
success:function(response)
{
var userRole = "<?php echo $userRole; ?>";
var string = "";
//string += '<input type="hidden" value="showCountryInfo" name="action"/>';
string += '<table id="tbl_countries" class="table table-bordered table-hover">';
string += '<tr>';
string += '<th>Flag</th>';
string += '<th>Country Name</th>';
string += '<th width=200px>Region</th>';
string += '<th>Surface Area</th>';
string += '<th>Population</th>';
string += '<th width=150px>Independent Year</th>';
string += '<th width=100px>City Details</th>';
if (userRole === "admin")
{
string += '<th width=100px>More Details</th>';
string += '<th width=100px>Update Details</td>';
string += '<th width=100px>Upload Flag</td>';
}
string += '</tr>';
/* from result create a string of data and append to the div */
$.each( response, function( key, value )
{
//var base64URL = "";
$("#records").empty();
string += "<tr>";
//string += "<td><img src='"+value['image']+"'/></td>";
//string += "<td><img src='data:image/png;base64, "+base64URL+"'/></td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' data-id='" + value['A3Code'] + "'>View</button>" + "</td>";
//string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' value='" + value['A3Code'] + "'>View</button>" + "</td>";
string += "<td>"+value['Name']+"</td>";
string += "<td>"+value['Region']+"</td>";
string += "<td>"+value['SurfaceArea']+"</td>";
string += "<td>"+value['Population']+"</td>";
string += "<td>"+value['IndepYear']+"</td>";
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#cityModal' id='city_details' name='city_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
if (userRole === "admin")
{
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#countryModal' id='more_details' name='country_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#updateModal' id='update_HOS' name='update_HOS' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-edit'></i></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#uploadModal' id='upload_flag' name='upload_flag' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-flag'></i></button>" + "</td>";
}
string += "</tr>";
});
string += '</table>';
$("#records").append(string);
}
});
}
/*$(document).on('click', '#btnView', function(){
window.location.href = "view_flag.php";
});*/
$(document).on('click', '#btnView', function(){
var value = $(this).attr('data-id');
window.location.href = "view_flag.php?A3Code=" + value;
});
/*//For view flag function
$("#btnView").on('click', function(e) {
window.location.href = "view_flag.php";
});*/
/*$("#view_flag").on("click",function()
{
window.location.href = "view_flag.php";
});*/
//For search country function
$("#search-btn").on("click", function ()
{
if(document.getElementById("search").value.length < 3)
{
alert("The characters MUST NOT be less than 3!");
return false;
}
$("#records").empty();
$(".records").empty();
$('.searchResults').empty();
var searchCountry = $("#search").val();
$.get(
'searchCountryInfo.php',
{id: searchCountry}, //left->sql id ,right->script id
function (data)
{
if (!$.trim(data)){
alert("No country with that name is found!");
return false;
}
var userRole = "<?php echo $userRole; ?>";
var string = "";
//string += '<input type="hidden" value="searchCountryInfo" name="action"/>';
string += '<table id="tbl_countries" class="table table-bordered table-hover">';
string += '<tr>';
string += '<th>Flag</th>';
string += '<th>Country Name</th>';
string += '<th width=200px>Region</th>';
string += '<th>Surface Area</th>';
string += '<th>Population</th>';
string += '<th width=150px>Independent Year</th>';
string += '<th width=100px>City Details</th>';
if (userRole === "admin")
{
string += '<th width=100px>More Details</th>';
string += '<th width=100px>Update Details</td>';
string += '<th width=100px>Upload Flag</td>';
}
string += '</tr>';
// var base64URL = getBase64(data[0]['image']);
// console.log(base64URL);
/* from result create a string of data and append to the div */
$.each( data, function( key, value )
{
$("#records").empty();
string += "<tr>";
//string += "<td>"+"<img src='data:image/png;base64,base64_encode("+value['image']+")"+"'/>"+"</td>";
//string += "<td>"+"<img src='data:image/jpeg;base64, "+base64URL+"'/></td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' data-id='" + value['A3Code'] + "'>View</button>" + "</td>"; string += "<td>"+value['Name']+"</td>";
string += "<td>"+value['Region']+"</td>";
string += "<td>"+value['SurfaceArea']+"</td>";
string += "<td>"+value['Population']+"</td>";
string += "<td>"+value['IndepYear']+"</td>";
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#cityModal' id='city_details' name='city_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
if (userRole === "admin")
{
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#countryModal' id='more_details' name='country_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#updateModal' id='update_HOS' name='update_HOS' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-edit'></i></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#uploadModal' id='upload_flag' name='upload_flag' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-flag'></i></button>" + "</td>";
}
string += "</tr>";
});
string += '</table>';
$("#records").append(string);
}
);
}); // end of search function
}); //end of big function
</script>
Your help will be really appreciated. Thank you.

How do I show back the plus button when delete image?

My html code is like this :
<input type='file' multiple style="display: none;" id="upload-file" />
<?php
for($i=0;$i<5; $i++) { ?>
<div class="img-container" id="box<?php echo $i ?>" data-status="0">
<button type="submit" class="btn btn-primary upload-add-product"<?php
if($i!=0) echo' style="display:none;"'; ?> >
<i class="glyphicon glyphicon-plus"></i>
</button>
<button style="display: none;" class="btn btn-danger show-button">
<i class="glyphicon glyphicon-trash"></i>
</button>
</div>
<?php } ?>
My javascript code is like this :
...
$(document).on('click',".show-button",function(){
var imgTmpl = '<div class="img-container">'+
'<button style="display: none;" type="submit" class="btn btn-danger show-button">'+
'<i class="glyphicon glyphicon-trash"></i>'+
'</button></div>';
$(this).parent().remove();
$('body').append(imgTmpl);
});
Demo and full code is like this : http://phpfiddle.org/main/code/9kb1-r47h
My problem is : when I uploaded 5 images. Then I delete 1 image. Plus icon does not appear again.
How can I solve this problem?
change your code like this , it is work for me,
<style type="text/css">
.img-container {
width: 162px;
height: 142px;
border: 2px solid black;
float: left;
margin-right: 5px;
position: relative;
}
.delete-button {
position: absolute;
left: 0;
}
.upload-add-product {
margin-top: 55px;
margin-left: 55px;
}
.img-container .show-button { position: absolute; top: 0; left: 0; }
</style>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<input type='file' multiple style="display: none;" id="upload-file" />
<div class="images-area">
<?php
for($i=0;$i<5; $i++) { ?>
<div class="img-container" id="box<?php echo $i ?>" data-status="0" data-index="<?=$i?>">
<?php if ($i == 0): ?>
<button type="submit" class="btn btn-primary upload-add-product">
<i class="glyphicon glyphicon-plus"></i>
</button>
<?php endif; ?>
</div>
<?php } ?>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on('click','.upload-add-product',function(){
$("#upload-file").click();
});
$(function () {
$(":file").change(function () {
var noOfFiles = this.files.length;
for(var i=0; i < noOfFiles; i++) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[i]);
}
});
});
function imageIsLoaded(e) {
var imgTmpl = '';
var IsImgAdded=false;
$('.img-container').each(function(){
if($(this).find('img').length==0 && IsImgAdded==false){
$(this).append(imgTmpl);
IsImgAdded=true;
$(this).attr('data-status',1);
//$(this).find('.upload-add-product').hide();
//$(this).find('.show-button').show();
var i = $(this).closest('.img-container').data('index');
var imgTmpl ='<img height="142" width="162" src='+e.target.result+'>'+
'<button type="button" class="btn btn-danger delete-button">'+
'<i class="glyphicon glyphicon-trash"></i>'+
'</button>';
$('#box'+i).html('');
$('#box'+i).append(imgTmpl);
if(i<5) {
$('#box'+(i+1)).html('<button type="button" class="btn btn-primary upload-add-product">'+
'<i class="glyphicon glyphicon-plus"></i>'+
'</button>');
}
$('.img-container').each(function(){
if( $(this).attr('data-status') != 1){
$(this).find('.upload-add-product').show();
return false;
}
})
}
});
};
$(document).on('click','.delete-button',function(){
var i = $(this).closest('.img-container').attr('data-index');
$('#box'+i).remove();
$('.images-area').append('<div class="img-container" data-status="0"></div>');
var blank = 0;
$('.img-container').each(function(i){
$(this).attr({'id':'box'+i,'data-index':i});
if(($(this).attr('data-status') == 0) && (blank == 0)) {
console.log("k");
blank = i;
}
});
if($('.img-container').find('.upload-add-product').length == 0) {
$('#box'+blank).append('<button type="button" class="btn btn-primary upload-add-product">'+
'<i class="glyphicon glyphicon-plus"></i>'+
'</button>');
}
});
</script>
Demo is here
May be it helps you...
Reason
You didn't even add the + button back in. I'd also suggest you look at template literals to help with formatting and multi-lined code.
You need to make sure that when you reach the end, that instead of having it set as none and waiting for something else to prompt it back to block or w/e, show it as block or w/e, intially
Updated parts:
$(document).on('click',".show-button",function(){
let pos;
let i = 0;
let parent = $(this).parent()[0];
$(".img-container").each( function() {
if (this == parent)
{
pos = i;
}
i++;
});
let show = (pos === 4) ? "block" : "none";
var imgTmpl = '<div class="img-container" data-status="0">'+
'<button style="display: ' + show +'" type="submit" class="btn btn-primary upload-add-product" onclick="upload_click();">' +
'<i class="glyphicon glyphicon-plus"></i>' +
'</button>' +
'<button style="display: none;" type="submit" class="btn btn-danger show-button">'+
'<i class="glyphicon glyphicon-trash"></i>'+
'</button></div>';
//console.log($(this).parent());
$(this).parent().remove();
$('body').append(imgTmpl);
});
function upload_click()
{
$("#upload-file").click();
}
http://phpfiddle.org/main/code/xzq8-h3ub
Prerequisite:
Assign id to your delete button
Then On click of delete button, check if id =0 and accordingly apply style to your plus button as below.
Last step is to append newly created plus button to current div.
$(".btn-danger").click(function(){
$id=this.id;
if($id!=0){
var r= $('<button type="submit" class="btn btn-primary upload-add-product" style="display:none;">
<i class="glyphicon glyphicon-plus"></i>
</button>');
}
else{
var r= $('<button type="submit" class="btn btn-primary upload-add-product">
<i class="glyphicon glyphicon-plus"></i>
</button>');
}
$(this).parent().append($r);
});
Let me know if this doesn't work.

Read and write excel using javascript and hta

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.

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

Categories