I want to take out the date validation(a validation to my code to validate year between 1930 and the current year and if it's not correct it should print an error) to another separate new function, Instead of the Addmovie function.
i want to make another new function called datevalidation and I want to add date validation, which is currently in the addmovie function.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Week 07 Pass Submission</title>
<script src="./w7p.js"></script>
</head>
<body>
<header>
<h1>Week 07 Pass Submission</h1>
</header>
<article>
<form>
<label for="movie">Movie title</label>
<input type="text" id="movie" /><br /><br />
<span id="yearValidation" style="color: red"></span>
<br />
<label for="year">Release year</label>
<input type="text" id="year" /><br /><br />
<input type="button" id="add" value="Add">
<input type="button" id="show" value="List All">
</form><br />
<div style="padding-left: 20px;" id="list"></div>
</article>
</body>
</html>
JavaScript Code
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year');
var year = document.getElementById('year').value;
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
} else {
document.getElementById('yearValidation').innerHTML = '';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;
You can declare a separate function dateValidation() and call it inside addMovie()
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function dateValidation(year,currentYear){
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year').value;
dateValidation(year,currentYear);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;
Related
I am 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 I select a year and filter it (for example if I select 2020) it says that the records are not available. I have included the link to my appscript and some images to explain my self better. Thank you so much.
Before filtering it
After filtering it
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;
var user = document.getElementById("currentUser").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(user,filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
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>
<h2> Resident Payment Status Portal</h2>
<div id="loginDisplay" style="padding: 10px;" >
<div class="form-row">
<div class="form-group col-md-3">
<label>User Name</label>
<input type="text" id="username" class="form-control" required/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label>Password</label><br>
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<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 id ="myFilter" class="form-group"></div>
<div id="displayRecords" style="padding: 10px;" ></div>
<!----Paypal Button-------->
<hr>
<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>
<!-----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>
When I saw your script, I noticed that var user = document.getElementById("currentUser").value; is used at filter() in Javascript side,. And, at GetRecords in GAS side, it seems that the user name used at the login is required to be used. In this case, I thought that user of var user = document.getElementById("currentUser").value; might be different from the user name, and this might be the reason of your issue. So, how about the following modification?
From:
function filter(){
var filterStr = document.getElementById("filterYear").value;
var user = document.getElementById("currentUser").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(user,filterStr);
}
To:
function filter(){
var filterStr = document.getElementById("filterYear").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(username, filterStr);
}
username has already been declared as the global variable. I thought that this value might be required to be used for GetRecords at GAS side.
I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
Good morning, I tried to push a temporaly value to a JSON file with the comand "MyJSON.name.push" but it tells me: "Undefined its not an object". I tried some forms and with javascript arrays worked but I need to do it on external JSON file. The error only appears if I click some button. Someone can help me?
Thanks you.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) MyJSON.push('{name:"url",url:"url1"}')
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.name.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.urls.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.SSL= SSL;
}
JSON FILE(json.json):
var MyJSON = [{
name:"Google",
url: 'google.es',
},
{
name:"Yahoo",
url: 'yahoo.com',
}
]
Change your this.Add() function like this:
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.push({"name":url,"url":url1})
el.value = '';
this.FetchAll();
}
}
I'm trying to pick a value from JSON and insert it on a diferents text boxes but it show the value "undefined". The objective is insert link on name space and link space and save it on LocalStorage and some statick values like google and yahoo. Please can someone help me? Thanks you so much.
EDIT: Now is solved, and now dont work the buttons, some one? Please
NEW PROBLEM:The error only appear if I press the buttons (it don't create the buttons).
ERROR: Can't find variable SSL
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = ss =function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.name.push(url.trim());
el.value = '';
this.FetchAll();
}
if (url) {
MyJSON.url.push(url1.trim());
el1.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.urls.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.name.splice(item, 1);
this.FetchAll();
};
}
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
}
I created a Chicago employee search index and wanted to create an alert when there are no matching records found, but can't seem to be able to find out what value I need to put in for when it's empty. Ideally, when the function get's submitted and no results are found, it would push an alert onto the screen indicating no matching records found.
The alert right now is located in the submit function in the last bit of code posted
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
})
}
<!doctype html>
<html>
<head>
<title>Salary Info Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="ChicagoEmployees.js"></script>
<script src="demoLS.js"></script>
</head>
<body>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
</body>
</html>
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
if (searchKey.isEmpty()) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
If I understand your question correctly, you can check if there's any matching data at the end of the getlist()
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
// ... codes ...
callBack(results);
// like this
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>