doGet fails when same commands are called as a subfunction within it - forms

Trying to learn Google Web Apps, I'm having the hardest time in 4 years of studying Google services. At this point, with help from other people, I have assembled a Web App form which successfully processes a few questions and accepts the submission of a file, sending the file to a folder on my Google Drive, appending the form answers to a Google Sheet, and sending me an email alerting me to the form submission. I think I understand how it works, but in trying to make the simplest of changes to it, it stopped working and gave me an error message I don't what to do with.
The form requires the user to upload an image of their COVID vaccination card. Since some people have more than one card, the form allows the user to upload more than file. This screen shot shows what the form displays upon successful submission.
The form fields and their answers remain in place, and below them appears the message "Uploaded successfully! You may upload another." What I want to have happen, besides a message like this appearing, is for all form fields and their answers disappear except for the Vacc Card/Choose File and Submit buttons.
So, I am trying to follow the instructions in this video from the highly popular YouTube Channel Learn Google Sheets & Excel Spreadsheets: Create Views (Pages) in Web App - Google Apps Script Web App Tutorial - Part 7
In this video, we see how to make the submission of a Web App form add to the current URL the string "?v=form" or "?v=whatever" and have the DoGet(e) function offer a different HTML file depending on whether the URL contains "&v" and if does, what follows that.
However, in following THE VERY FIRST STEP in the instructions, the App stopped working. All I did was cut what was inside the function doGet(e), place it inside a new function loadForm(), and put inside the doGet a calling of that function:
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
}
This one change caused the App to fail, returning nothing but a screen reading "The script completed but did not return anything."
My code:
/*
* Original doGet function; works fine. */
// function doGet(e){
// return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
// .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
// }
/** Step that caused this to fail: */
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} // else {HtmlService.createHtmlOutput('<h1>Hello<h1>')} // This would have been the next step, and the step after that making a second HTML file.
// Commenting out this step did NOT help.
}
function loadForm(){
return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
} /** There you have it. All that follows is part of what works. */
function uploadFiles(formObject) {
var folderID = "1nvhxUoj9uRlE0KpBNjW3cosIuuRpAQly"; // Massage / VaccinationCards
try {
var folder = DriveApp.getFolderById(folderID);
var fileUrl = "";
//Upload file if exists
if (formObject.myFile.length > 0) {
var name = formObject.name;
var namePref = formObject.namePref;
var pronouns = formObject.pronouns;
var ready = formObject.ready;
var email = formObject.email;
var phone = formObject.phone;
var callTimes = formObject.callTimes;
var questions = formObject.questions;
var blob = formObject.myFile;
var file = folder.createFile(blob);
fileUrl = file.getUrl();
} else {
fileUrl = null;
}
SpreadsheetApp.openById("1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50").getSheetByName("cards")
.appendRow([name, namePref, pronouns, ready, email, phone, callTimes, questions, fileUrl, new Date()]);
GmailApp.sendEmail('atiqzabinski#gmail.com', 'New Vax Card Uploaded!', 'Hey sweetie, smells like business! https://docs.google.com/spreadsheets/d/1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50/edit', {name: 'Vacc Card Robot'});
return fileUrl;
} catch (error) {
return error.message;
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style = "background:none transparent;">
<!-- <link href="/tpm-styles.css" rel="stylesheet" type="text/css"> -->
<link href="https://transformphillymassage.com/tpm-styles.css" rel="stylesheet" type="text/css">
<link href="https://transformphillymassage.com/formstyles.css" rel="stylesheet" type="text/css">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p>
<label for="FormControlFile">Legal Name:</label>
<input name="name" class="form-control-file" type="text" size="35" required/>
<br>
<label for="FormControlFile">Preferred Name:</label>
<input name="namePref" class="form-control-file" type="text" size="30">
<br> <label for="FormControlFile">Pronouns:</label>
<input name="pronouns" class="form-control-file" type="text" size = "35">
</p>
<p>
<label for="FormControlFile">Choose One:</label>
<!-- <select id = "id_ready" name = "ready" class="form-control-file" required/> -->
<!-- <select id = "id_ready" name = "ready" required/> -->
<select name = "ready" class="form-control-file" required/>
<option value = "I'm ready to book!">I'm ready to book!</option>
<option value = "I have questions.">I have questions.</option>
</select>
</p>
<p>
<label for="FormControlFile">email:</label>
<input name="email" class="form-control-file" type="text" size = "40" required/>
<br>
<label for="FormControlFile">Phone Number:</label>
<input name="phone" class="form-control-file" type="text" size = "28" />
<br>
<label for="FormControlFile">Best Times To Call:</label><br>
<input name="callTimes" class="form-control-file" type="text" size="50"/>
</p>
<p>
<label for="FormControlFile">Vacc Card:</label>
<input name="myFile" class="form-control-file" type="file" required/>
</p>
<p>
<label for="FormControlFile">Questions / Comments:</label><br>
<textarea name ="questions" class="form-control-file" cols="45" rows="4"></textarea>
<br>
<button type="submit"><span class="charm spanlavender">Submit</span></button>
</p>
</form>
<div id="urlOutput"></div>
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject){
google.script.run.withSuccessHandler(updateUrl).withFailureHandler(onFailure).uploadFiles(formObject);
}
function updateUrl(url) {
var div = document.getElementById('urlOutput');
if(isValidURL(url)){
div.innerHTML = '<div class="alert alert-success" role="alert">Uploaded successfully!<br>You may upload another.</div>';
// document.getElementById("myForm").reset();
} else {
//Show warning message if file is not uploaded or provided
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ url +'!</div>';
}
}
function onFailure(error) {
var div = document.getElementById('urlOutput');
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ error.message +'!</div>';
}
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null);
}
</script>
</body>
</html>

return is missing on the else part of your if-else statement
Replace your doGet function by
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} else {
return HtmlService.createHtmlOutput('<h1>Hello<h1>')
}
}
Below are a couple of function that could be used to debug your doGet function by using the Google Apps Script editor.
/**
* Test case 1: v parameter equal to 'form'
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
e.parameter.v = 'form';
doGet(e);
}
/**
* Test case 2: No v parameter
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
doGet(e);
}
Related
Google App Script how to load different pages using HTML Service?
How can I test a trigger function in GAS?
getting parameters from a url returns 'parameter is undefined"
How to get a URL string parameter passed to Google Apps Script doGet(e)
Serve separate HTML pages Google apps script not working
doGet(e) parameter undefined

Related

Why Is my script freezing up when I hit enter?

The majority of the Add-on is good but whenever I hit enter (which is, in my opinion, the most common way to submit a form, for example, a login form), but all it does is blank out.
I've tried linking the script with a onkeydown like so:
<div onkeydown="handle(event)">blagh blagh blagh</div>
but I still get the same results:
<html>
<form id='myForm' style="font-family:Georgia;">
<table>
<tr><td><h2>Enter your Password</h2></td></tr>
<tr><td><p>DO NOT HIT ENTER ON YOUR KEYBOARD!!!!!</p></td></tr>
<tr><td><input name='password' type='password' value="" onkeypress="handle(event)"></td></tr>
<tr><td><div id="submitbuttcontainer"><img id="submitloader" style="display:none;" src='https://lh6.googleusercontent.com/-S87nMBe6KWE/TuB9dR48F0I/AAAAAAAAByQ/0Z96LirzDqg/s27/load.gif' /><input id="submitbutt" type='button' onclick='showWorking();google.script.run.withSuccessHandler(onSuccess).decodeForRequest(document.getElementById("myForm"));' name="Submit" value="Submit"></div></td></tr>
</table>
</form>
<script>
function onSuccess(obj) {
document.getElementById('submitbutt').style.display="block";
document.getElementById('submitloader').style.display="none";
if(obj.status == 'success') {
google.script.host.closeDialog();
browser.msgbox('Access Granted', browser.buttons.OK)
}
else {
browser.msgbox('ALERT!!','!OOF!','Incorrect Password. Please retry', browser.buttons.OK);
}
}
function showWorking() {
document.getElementById('submitbutt').style.display="none";
document.getElementById('submitloader').style.display="block";
}
function handle(e){
if(e.keyCode === 13)
document.getElementById('submitbuttcontainer').click();
}
</script>
</html>
All I'm trying to do is get the form to submit when I hit enter and not blank out. I always hit enter to submit a form but in this case all it does is blank out the form and all I have is whiteness.
Here's the link for the complete source code (don't know if this will work because I'm in a school district):
https://script.google.com/a/bcsdschools.net/d/1_YUx4ZP3qEWVcFMc-MvfEYX2S34r7-b4M0iRlE_JQa81T3ZubN5OeISa/edit)
Problem
Hitting enter key results in form submission (which is explicitly forbidden in Apps Script due to its client-to-server communication implementation).
Solution 1 - handle inputs individually
Add preventDefault() to a keydown event if key is enter (btw, keypress event is deprecated, see reference on MDN, use the keydown / keyup instead):
var ENTER_CODE = 13;
function handle(e) {
if(e.keyCode === ENTER_CODE) {
e.preventDefault();
document.getElementById('submitbuttcontainer').click();
}
}
Solution 2 - handle form submit
You can listen for a submit event on your form instead and invoke preventDefault() as the only statement in event handler or handle form submission at the same time if you expect form to be submitted on enter key hit:
//assumption: form is initiated elsewhere in code;
form.addEventListener('submit', (event) => {
event.preventDefault();
//handle submission;
});
You can also prevent all forms from being submitted to make the setup flexible:
(() => {
const { forms } = document;
Object.values(forms).forEach(
form => form.addEventListener("submit", (e) => e.preventDefault())
);
})();
Or, alternatively, use event delegation and register one listener on the document since the event bubbles up:
document.addEventListener("submit", (e) => e.preventDefault());
Suggestion
Please, use addEventListener instead of on[event name here] attributes. This way is much more flexible and has the benefit of being concise and easy for others to read.
References
Handling forms in Apps Script guide
Why use addEventListener? MDN reference
I wanted to try to give you a complete answer, but I have to admit that I may know less about event handlers than you. But this seems to work for me.
aq4.html:
<html>
<head>
<script>
window.onload=function() {
preventFormSubmit1();
}
function preventFormSubmit1() {
console.log('preventFormSubmit1');
var form=document.forms['myForm'];
form.addEventListener('submit',function(e) {
e.preventDefault();
});
}
function handleFormSubmit(formObject) {
console.log('handleFormSubmit');
var first=document.forms['myForm']['first'].value;
var last=document.forms['myForm']['last'].value
var sheet=document.forms['myForm']['sheet'].value;
console.log('%s,%s,%s',first,last,sheet);
if(first.length>0 && last.length>0 && sheet.length>0) {
google.script.run
.withSuccessHandler(function(msg){
var div=document.getElementById('output');
div.innerHTML=msg;
var inputs=document.querySelectorAll('input[type=text]');
inputs[0].focus();
for(var i=0;i<inputs.length;i++) {
inputs[i].value='';
}
})
.processForm(formObject);
}else{
alert("Invalid or Incomplete Data");
}
}
console.log("MyCode");
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="first" /> First<br />
<input type="text" name="last" /> Last<br />
<select name="sheet">
<option value="Sheet1">Sheet1</option>
<option value="Sheet2">Sheet2</option>
</select> Sheet<br />
<input id="sub" type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
aq1.gs:
function processForm(formObject) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(formObject.sheet);
sh.appendRow([formObject.first,formObject.last]);
return Utilities.formatString('First: %s<br />Last: %s<br />Sheet: %s', formObject.first,formObject.last,formObject.sheet);
}
function runOne() {//This loads the dialog
var userInterface=HtmlService.createHtmlOutputFromFile('aq4').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Form Example")
}

angular 2, validate form if at least one input is typed

I'm quite new to Angular, and I've already searched the web, without finding a correct solution for my situation.
I have a dynamic form created by a *ngFor. I need to disabled the submit button if the inputs are all empty and show the alert div; but I need to enable the submit if at least one of those forms contains something different from ''.
Here is my html code
<form class="form-inline" #form="ngForm">
<div class="form-group" *ngFor="let meta of state.metaById; let i = index" style="margin: 5px">
<label>{{meta.nome}}</label>
<input type="text" class="form-control" #nome (blur)="inputInArray(nome.value, i);">
</div>
<button type="button" class="btn btn-primary" (click)="getCustomUnitaDocumentaliRow(this.param)" [disabled]="fieldNotCompiled">invia</button>
</form>
<div class="alert-notification" [hidden]="!fieldNotCompiled">
<div class="alert alert-danger">
<strong>Va compilato almeno un campo.</strong>
</div>
</div>
and here is my Typescript code
inputInArray(nome: string, indice) {
if (this.state.controlloMetaId = true) {
this.state.metadatoForm[indice] = nome;
}
// this.fieldNotCompiled = false;
for (const i in this.state.metaById) {
console.log(this.state.metadatoForm);
if (isUndefined(this.state.metadatoForm[i]) || this.state.metadatoForm[i] === '') {
this.fieldNotCompiled = true && this.fieldNotCompiled;
} else {
this.fieldNotCompiled = false && this.fieldNotCompiled;
}
console.log(this.fieldNotCompiled);
}
With this code I can check the first time a user type something in one input, but it fails if it empty one of them (or all of them)
Thanks for your time
UPDATE
Check if any input got a change that is different from empty or space, just by doing:
<input ... #nome (input)="fieldNotCompiled = !nome.value.trim()" ....>
DEMO
You can set a listener to the form changes:
#ViewChild('form') myForm: NgForm;
....
ngOnInit() {
this.myForm.valueChanges.subscribe((value: any) => {
console.log("One of the inputs has changed");
});
}

SharpSpring - Prevent form from automatically appearing if user has filled out form (without relying on cookies)

Ok, this is related to the question I asked a short while ago: Silverstripe/PHP/jQuery - Once form has been filled out by user, prevent it from automatically appearing for each visit
Something has changed since then. Per request of the client, the form must not automatically appear if the user has already filled it out and has thus been placed into SharpSpring. Originally, I was creating a cookie on successful form submission using JavaScript. However, the latest concern is that it's not effective enough as cookies are registered only to certain devices and browsers, and users can clear their cookies at any time.
Essentially, the desired result is to prevent the form from automatically appearing if the user has been registered in SharpSpring (a separate domain) without having to rely on cookies.
Has anyone ever attempted something like this, checking to see if a user has submitted a form to another domain?
For reference, here is the form code I have setup:
<?php
/*
Plugin Name: SharpSpring Form Plugin
Description: A custom form plugin that is SharpSpring-compatible and uses HTML, CSS, jQuery, and AJAX
Version: 1.0
*/
define('SSCFURL', WP_PLUGIN_URL . "/" . dirname(plugin_basename(__FILE__)));
define('SSCFPATH', WP_PLUGIN_DIR . "/" . dirname(plugin_basename(__FILE__)));
function sharpspringform_enqueuescripts()
{
wp_enqueue_script('jquery-src', SSCFURL . '/js/jquery.js', array('jquery'));
wp_enqueue_script('jquery-ui', SSCFURL . '/js/jquery-ui.js', array('jquery'));
wp_enqueue_script('boootstrap', SSCFURL . '/js/bootstrap.js', array('jquery'));
wp_localize_script('sharpspringform', 'sharpspringformajax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'sharpspringform_enqueuescripts');
function sharpspringform_show_form()
{
wp_enqueue_style( 'boilerplate', SSCFURL.'/css/boilerplate.css');
wp_enqueue_style( 'bootstrapcss', SSCFURL.'/css/bootstrap.css');
wp_enqueue_style( 'bookregistration', SSCFURL.'/css/Book-Registration.css');
wp_enqueue_style( 'formstyles', SSCFURL.'/css/styles.css');
?>
<div class="mobile-view" style="right: 51px;">
<a class="mobile-btn">
<span class="glyphicon glyphicon-arrow-left icon-arrow-mobile mobile-form-btn"></span>
</a>
</div>
<div class="slider register-photo">
<div class="form-inner">
<div class="form-container">
<form method="post" enctype="multipart/form-data" class="signupForm" id="browserHangFormPV">
<a class="sidebar">
<span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
</a>
<a class="closeBtn">
<span class="glyphicon glyphicon-remove"></span>
</a>
<h2 class="text-center black">Sign up for our newsletter.</h2>
<p class="errors-container light">Please fill in the required fields.</p>
<div class="success">Thank you for signing up!</div>
<div class="form-field-content">
<div class="form-group">
<input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
autofocus="">
</div>
<div class="form-group">
<input class="form-control CompanyTxt" type="text" name="company" placeholder="*Company"
autofocus="">
</div>
<div class="form-group submit-button">
<button class="btn btn-primary btn-block button-submit" type="button">SIGN ME UP</button>
<img src="/wp-content/plugins/sharpspring-form/img/ajax-loader.gif" class="progress" alt="Submitting...">
</div>
</div>
<br/>
<div class="privacy-link">
<a href="[privacy policy link]" class="already" target="_blank"><span
class="glyphicon glyphicon-lock icon-lock"></span>We will never share your information.</a>
</div>
</form>
<input type="hidden" id="gatewayEmbedID" value="<?php echo get_option( 'pv_signup_sharpspring_ID' ); ?>" />
<script type="text/javascript">
var embedID = document.getElementById("gatewayEmbedID").value;
var __ss_noform = __ss_noform || [];
__ss_noform.push(['baseURI', 'https://app-3QNAHNE212.marketingautomation.services/webforms/receivePostback/[redacted]']);
__ss_noform.push(['form', 'browserHangFormPV', embedID]);
__ss_noform.push(['submitType', 'manual']);
</script>
<script type="text/javascript" src="https://koi-3QNAHNE212.marketingautomation.services/client/noform.js?ver=1.24" ></script>
</div>
</div>
</div>
<?php
}
function sharpspringform_shortcode_func( $atts )
{
ob_start();
sharpspringform_show_form();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'sharpspringform', 'sharpspringform_shortcode_func' );
The form submission code with generates a cookie using JS:
;
(function ($) {
$(document).ready(function () {
var successMessage = $('.success');
var error = $('.errors-container');
var sharpSpringID = $('#gatewayEmbedID').val();
var submitbtn = $('.button-submit');
var SubmitProgress = $('img.progress');
var formdata = {};
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
submitbtn.click(function (e) {
resetErrors();
postForm();
});
function resetErrors() {
$('.signupForm input').removeClass('error-field');
}
function postForm() {
$.each($('.signupForm input'), function (i, v) {
if (v.type !== 'submit') {
formdata[v.name] = v.value;
}
});
submitbtn.hide();
error.hide();
SubmitProgress.show();
$.ajax({
type: "POST",
data: formdata,
url: '/wp-content/plugins/sharpspring-form/sharpsring-form-submission.php',
dataType: "json"
}).done(function (response) {
submitbtn.show();
SubmitProgress.hide();
if (response.errors) {
error.show();
var errors = response.errors;
errors.forEach(function (error) {
$('input[name="' + error + '"]').addClass('error-field');
})
}
else {
__ss_noform.push(['submit', null, sharpSpringID]);
setCookie('SignupSuccess', 'NewsletterSignup', 3650);
$('#browserHangFormPV')[0].reset();
$('.form-field-content').hide();
successMessage.show();
$('.button-submit').html("Submitted");
}
});
}
});
}(jQuery));
The jQuery code that sets up the form sliding animation and popup feature, as well as checks for the existence of the JS cookie created on successful form submit:
jQuery.noConflict();
(function ($) {
$(document).ready(function () {
//This function checks if we are in mobile view or not to determine the
//UI behavior of the form.
checkCookie();
window.onload = checkWindowSize();
var arrowicon = $(".arrow");
var overlay = $("#overlay");
var slidingDiv = $(".slider");
var closeBtn = $(".closeBtn");
var mobileBtn = $(".mobile-btn");
//When the page loads, check the screen size.
//If the screen size is less than 768px, you want to get the function
//that opens the form as a popup in the center of the screen
//Otherwise, you want it to be a slide-out animation from the right side
function checkWindowSize() {
if ($(window).width() <= 768) {
//get function to open form at center of screen
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(formModal, 5000);
function formModal() {
slidingDiv.addClass("showForm")
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
}
}
}
else {
//when we aren't in mobile view, let's just have the form slide out from the right
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(slideOut, 5000);
function slideOut() {
slidingDiv.animate({'right': '-20px'}).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("SignupSuccess");
if (user != "") {
return true;
} else {
return false;
}
}
/*
------------------------------------------------------------
Functions to open/close form like a modal in center of screen in mobile view
------------------------------------------------------------
*/
mobileBtn.click(function () {
slidingDiv.addClass("showForm");
slidingDiv.removeClass("hideForm");
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
});
closeBtn.click(function () {
slidingDiv.addClass("hideForm");
slidingDiv.removeClass("showForm");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay")
mobileBtn.removeClass("hideBtn");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
});
/*
------------------------------------------------------------
Function to slide the sidebar form out/in
------------------------------------------------------------
*/
arrowicon.click(function () {
if (slidingDiv.hasClass('open')) {
slidingDiv.animate({'right': '-390px'}, 200).removeClass('open');
arrowicon.addClass("glyphicon-arrow-left");
arrowicon.removeClass("glyphicon-arrow-right");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
} else {
slidingDiv.animate({'right': '-20px'}, 200).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
});
});
}(jQuery));
I'm confused by the WordPress code here, rather than SilverStripe, it's not clear in your question which platform you're using.
Basically, if you want something more robust than cookies, you'll need to store the registration in the database and check it there (assuming the registration form is on your site). This means you handle the form submission on your site, send the data to the remote site and check the responses, and if all goes well, save the fact that the user has registered remotely into your database where you can check when deciding whether to show the form or not, next time.
If you don't have access to the registration form, or you want to also notice registrations made independently of your site, then you need to have an API you can query on the remote site in order to see if the user is registered.
I found a sharpspring API, but I'm not sure if it's relevant.

Use code captcha in two forms

I have two forms on a page containing Google captcha code, but only one code works. Does anyone know if you can use the same code with the same key on two forms on the same page?,
Thks,
Yes, you can. But you have to explicitly render the widget as mentioned on the developer guide
you should use something like this on your front end(taken from the developer guide):
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
I just wanted a HTML snipped which I can insert multiple times, each time displaying another captcha. Also, I did not want to take care for specific IDs assigned to the containers, which would be very annoying when multiple formulars still appearing on one page will be designed and rendered independently. Here is my solution.
<div class="g-recaptcha"></div>
<script type="text/javascript"><![CDATA[
function renderCaptchas() {
var captchaNodes = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < captchaNodes.length; i++) {
var captchaNode = captchaNodes[i];
if (!captchaNode.captchaRendered) {
captchaNode.captchaRendered = true;
grecaptcha.render(captchaNode, {"sitekey": "YOUR_SITE_KEY"});
}
}
}
]]></script>
<script src="https://www.google.com/recaptcha/api.js?onload=renderCaptchas&render=explicit" async="async" defer="defer"></script>

dynamic creation of textbox

while i create textbox dynamically i can able to add any no
of textbox while i delete only last textbox got deleted after it
an throws exception.
<html>
<head>My page </html>
<body>
<div id="firstdiv">
<input type="text" id="text" id="text1" value=""/>
<input type="button" id="butt" name="it's okay" value="+" onclick="text_add()"/>
<input type="button" id="butt1" name="it's okay" value="-" nclick="text_remove()"/>
</div>
</body>
<script type="text/javascript">
var i=0;
function text_add()
{
++i;
var bal=document.createElement("input")
bal.setAttribute("type","text");
bal.setAttribute("id","text"+i);
bal.setAttribute("name","bala");
firstdiv.appendChild(bal);
}
function text_remove()
{
try{
var a="\"";
a+="text"+(i);
a+="\"";
alert(a);
var bal=document.getElementById(a);
firstdiv.removeChild(bal);
--i;
}catch(e)
{
alert("Echo"+e);
}
}
</script>
</html>
chorme throws error: after deleting one text box like
EchoError: NOT_FOUND_ERR: DOM Exception 8
so you whant to add and remove textboxes.
and the latest textbox added shuld be removed?
so first you alreddy have a textbox in the dom witch will colide with your
naming
<input type="text" id="text" id="text1" value=""/>
is this an atemt to manualy add qoutes ? becus thats not part of the id
of the element
var a="\"";
a+="text"+(i);
a+="\"";
just give it the name normaly
var bal = document.getElementById("text" + i);
and you dont have to mess around with dom ids you can store
dom elements as normal objects so
something like this works fine
var textElements = [];
var firstdiv = document.getElementById("firstdiv");
function text_add() {
var bal = document.createElement("input");
bal.setAttribute("type","text");
bal.setAttribute("name","bala");
firstdiv.appendChild(bal);
textElements.push(bal);
}
function text_remove() {
firstdiv.removeChild(textElements.pop());
}
the pop method removes the last added item in the array