Pop-up form will not close after submit in Google Sheets - javascript

I'm using my function openDialog to display a custom HTML form. It will submit fine, but will not close the pop-up window after the form is submitted. I would like this form to either close after submitting, or show a "thank-you.html" with a "Close" button.
.gs
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index.html');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Pop up Form');
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index').setTitle('Adding Rows');
}
function doPost(e) {
Logger.log(e);
}
function sendText(data) {
var sheet = SpreadsheetApp.openById("some id").getActiveSheet();
sheet.appendRow([data.form_field_1, data.form_field_2, data.form_field_3, data.form_field_4]);
return 'success!';
}
HTML
<html>
<head>
<base target="_top">
</head>
<body>
<form onsubmit="sendText(event)" id="test-form">
<div>
<label>Field 1</label>
<input type="text" name="form_field_1" placeholder="Field 1" />
</div>
<div>
<label>Field 2</label>
<input type="text" name="form_field_2" placeholder="Field 2" />
</div>
<div>
<label>Field 3</label>
<input type="text" name="form_field_3" placeholder="Field 3" />
</div>
<div>
<label>Field 4</label>
<input type="text" name="form_field_4" placeholder="Field 4" />
</div>
<div>
<button type="submit" id="submit-form">Submit</button>
</div>
</form>
<script>
function sendText(e) {
e.preventDefault();
var data = {
form_field_1: e.target['form_field_1'].value,
form_field_2: e.target['form_field_2'].value,
form_field_3: e.target['form_field_3'].value,
form_field_4: e.target['form_field_4'].value
}
google.script.run
.withSuccessHandler(function(response) {
console.log(response);
window.close();
})
.sendText(data);
}
</script>
</body>
</html>
Not sure what I'm doing wrong

Found the fix by doing this.
<script>
function sendText(e) {
e.preventDefault();
var data = {
form_field_1: e.target['form_field_1'].value,
form_field_2: e.target['form_field_2'].value,
form_field_3: e.target['form_field_3'].value,
form_field_4: e.target['form_field_4'].value
}
google.script.run.withSuccessHandler(function(response) {
console.log(response);
google.script.host.close()
})
.sendText(data);
}
</script>

You need something like this:
function closepopup()
{
document.getElementById('test-form').style.display = 'none';
}
function sendtext()
{
if(jQuery('#test-form').valid())
{
var formurl = 'submit url';
jQuery.ajax({
type: "POST",
url: formurl,
data: jQuery('#test-form').serialize(true),
success: function()
{
// you can add here redirect the current page or success message
closepopup();
}
});
}
}
<div>
<button type="submit" id="submit-form" onclick="sendtext()">Submit</button>
</div>
I hope this will help!

Related

Sending user input text box value via jquery from a partial page to Controller

My partial view has a table with multiple rows with a button in each row (unique across each). When the button is pressed a jquery modal dialog is opened and the user can enter a value in a text box. That value is what i'm not able to get into a jquery variable to send to my MVC controller. All the jquery code is executed from the partial view.
I've tried every example I've seen on the web. I have code already that works, just not through a partial view.
CSHTML:
<form>
<div id="currentandnewtipamount">
<div>#Html.Label("Current Tip Amount: $")
<label for="CurrentTipAmount" ></label>
</div>
<br />
#Html.Label("Tip Edit Amount")
<input type="text" name="NewTipEditAmount" id="NewTipEditAmount" >
</div>
</form>
JQuery:
var TipEditDialog, RRN;
NewTipEditAmount = $("#NewTipEditAmount");
function SubmitTipEditAmount() {
NewTipEditAmount = $("#NewTipEditAmount").val().toString();
{
$.ajax({
type: "POST",
url: "/MyTransactions/UpdateTipAMT",
data: { 'NewTipEditAmount': NewTipEditAmount },
success: function (bool) {
//alert(bool);
}
});
}
}
Below is a working example in another part of the site that does not use a partial view.
JQuery:
var Logindialog, form;
loginusername = $("#loginusername"),
loginpassword = $("#loginpassword"),
loginnewpassword = $("loginnewpassword"),
loginconfirmnewpassword = $("loginconfirmnewpassword"),
allFields = $([]).add(loginusername).add(loginpassword);
function LoginUser() {
loginusername = $("#loginusername").val().toString();
loginpassword = $("#loginpassword").val().toString();
{
$.ajax({
type: "POST",
url: "/User/Login",
data: { 'loginusername': loginusername, 'loginpassword': loginpassword },
success: function (response) {
if (response === true) {
$("#Logindialog-form").dialog("close");
RunPasswordCheck(loginusername, loginpassword);
}
else {
alert("Something is not correct, try again please");
Logindialog.dialog("close");
}
}
});
}
}
CSHTML:
<div id="Logindialog-form" title="Log In" class="divloginformcontent">
<form class="loginformcontent">
<div id="usernameAndpassword" class="Usernamepassword">
<label for="username" class="loginfieldtext">Username</label>
<input type="text" name="loginusername" id="loginusername" class="loginfields" />
<br /><br />
<label for="password" class="loginfieldtext">Password</label>
<input type="password" name="loginpassword" id="loginpassword" class="loginfields" />
<br /><br />
</div>
<input type="submit" tabindex="-1" style="position: absolute; top: -1000px" id="LoginSubmit" /> #*tab index and style allows for the enter button to be used without messing up anything*#
</form>
**
Can you try using the Jquery in the page where Partial view is calling
instead of Inside Partial View.
**
Below is the code which ended up working for my situation. I seemed to need to have an 'id' for every element and reference them throughout the nesting in the jquery.
CSHTML:
<div id="EditTip-form" title="Edit Tip Amount" class="divloginformcontent">
<form class="loginformcontent" id="form">
<div id="currentandnewtipamount">
#Html.Label("Current Tip Amount: $") <label for="CurrentTipAmount" ></label>
<br />
#Html.Label("Tip Edit Amount")
<input type="text" name="NewTipEditAmount" id="NewTipEditAmount" class="forminput">
</div>
</form>
</div>
JQUERY:
function SubmitTipEditAmount() {
NewTipEditAmount = $('#EditTip-form #form #currentandnewtipamount #NewTipEditAmount').val();
{
$.ajax({
type: "POST",
url: "/MyTransactions/UpdateTipAMT",
data: { 'RRN': RRN, 'NewTipEditAmount': NewTipEditAmount },
success: function (bool) {
//alert(bool);
}
});
TipEditDialog.dialog("close");
}
}

Html form submit after ajax

Trying to make some database validation with Jquery Get method before submitting a form. But I get the error
Uncaught TypeError: form.submit is not a function
Got the logic form here
Simplified Code below (but the err is still there...)
<html>
<body>
<div id="insertCertificateForm">
<form action="/Certificates/Insert" method="post">
<div>
<label>Charge</label>
<input name="Charge" id="Charge" />
</div>
<input type="submit" value="Insert" class="btn btn-default" />
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#insertCertificateForm').submit(function (e) {
e.preventDefault();
var form = this;
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
form.submit();
}
else {
return false;
}
});
});</script>
</body>
</html>
Because after clicking button this would mean the current button and
insertCertificateForm was never a form anyways...it was Div
best would be to bind the form with an ID #myForm
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="insertCertificateForm">
<form id="Myform" action="/Certificates/Insert" method="post">
<div>
<label>Charge</label>
<input name="Charge" id="Charge" />
</div>
<input type="submit" value="Insert" class="btn btn-default" />
</form>
</div>
<script>
$('#insertCertificateForm').submit(function (e) {
e.preventDefault();
var form = $("#Myform");
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
form.submit();
} else {
return false;
}
});
});
</script>
</body>
</html>
and also load your scripts in the head
Your selector is wrong $('#insertCertificateForm'), if you want to do like this you need to add this id into your form <form id="insertCertificateForm" otherwise follow this way,
$('form').submit(function (e) {
e.preventDefault();
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
$(this).submit();
} else {
return false;
}
});
});
That's because you're calling this and not $(this) when declaring the form variable. You can either declare it as $(this) or use $(form) to submit the form.

Submitting two forms separately in one page with separate thankyou message

I've a page which have two different forms:
Form 1:
<form id="info-form" method="POST" action="">
<label for="name">What is your Name? </label>
<input required type="text" name="name" placeholder="Enter your full name here." />
<label for="email">What is your email ID? </label>
<input required type="email" name="email" placeholder="your.name#email.com" />
<label for="mobile-number">What is your 10-Digit Mobile Number? </label>
<input required type="text" name="mobile-number" maxlength="10" placeholder="Enter num." />
<label for="posting-place">What is your current place of residence? </label>
<input type="text" name="place" placeholder="Enter your current residing place here." />
<button type="submit" class="btn btn-lg btn-success">
  Submit
</button>
<button type="reset" class="btn btn-lg btn-warning">
Reset
</button>
</form>
Form 2:
<form id="contact-form" method="POST" action="">
<label for="name">What is your Name? </label>
<input type="text" name="name" placeholder="Enter your full name here." />
<label for="email">What is your email ID? </label>
<input type="email" name="email" placeholder="your email" />
<label for="message"> Your Message: </label>
<textarea id="message" name="message" rows="5" placeholder="Type in your message here"></textarea>
<button id="submit_button" type="submit" class="btn btn-lg btn-success">
Send
</button>
<button id="reset_button" type="reset" class="btn btn-lg btn-warning">
Reset
</button>
</form>
I then have these below thank you messages after the closing form tag of both the above two forms
Thank you message after submitting Form 1:
<div style="display:none;" id="thankyou_form">
<p><em>Thank You</em> for submitting!</p>
</div>
Thank you message after submitting Form 2:
<div style="display:none;" id="thankyou_contact">
<p><em>Thank You</em> for contacting! We will get back to you soon!</p>
</div>
I then have two script for displaying the thank you message on the same page after the form is submitted.
<script type="text/javascript">
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_contact").style.display = "inline";
}
else
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_contact").style.display = "none";
}
}
});
});
});
</script>
But when I submit the second form the thankyou message is also displayed is the first form. Also, the form is submitted twice.
Can you please inform me how to identify both the javascript separately? Or, Can I combine both the script into one but both submit buttons working independently of each other?
It would be very much helpful and also enlightening for me if you can point out my mistake.
P.S. I'm a beginner.
Edit1: The javascript code was modified (but currently non-working) as per suggestion from David. The new code is:
<script type="text/javascript">
$(function ()
{
$('form').submit(function (e)
{
if(e.target === 'form#info-form')
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
document.getElementById("thankyou_info").style.display = "inline";
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
}
}
});
}
if(e.target === 'form#contact-form')
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
document.getElementById("thankyou_contact").style.display = "inline";
}
else
{
document.getElementById("thankyou_contact").style.display = "none";
document.getElementById("sorry_contact").style.display = "inline";
}
}
});
}
});
});
</script>
Use event.target to determine which form is getting submitted, You need to refine your code as,
if(response.result == 'success')
{
// Determine if the submission came from "Info Form" or "Contact Form"
if(e.target === 'form#info-form')
{
document.getElementById("thankyou_form").style.display = "inline";
}
else
{
document.getElementById("thankyou_contact").style.display = "inline";
}
}
else
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_form").style.display = "none";
document.getElementById("thankyou_contact").style.display = "none";
}

Preview data form

I need some help, I have a form that before the 'Send' button have a select type 'check' if this is uncheck and the people click on 'send' the form show a pop up with the preview of the all data in the form, if the select is check and the people click on 'send' this is sending normal, but I would like change that, I would like change the select check to a button 'Preview' and when the people click show the pop up with the preview, and the send buttom continue normal send the form.
this is the code for the pop up with the rule if is check or uncheck.
function check_form() {
var url = "process_estaform.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#estafrm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#dialog").html(data);
if($("#senditornot").prop("checked") === false ) {
$("#dialog").attr("title","This dialog box will automatically close.");
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
},
error :function() {
$("#dialog").html(data);
$("#dialog").attr("title","This dialog box will automatically close.");
if($("#senditornot").prop("checked") === false ) {
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
}
});
}
code html.
<div class="container">
<input type="checkbox" name="sendit" id="senditornot" />
</div>
<br>
<div class="container">
<div align="center">
<input type="submit" id="submitter" value="Submit" />
</div>
</div>
img form
Add following before function check_form.
$("#preview").click(function()
{
var previewData = $("#estafrm").serialize();
$("#dialog").html(previewData);
})
add preview button in code.html
<input type="button" name="preview" id="preview" value="preview" />
Added complete code.
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function check_form() {
var url = "process_estaform.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#estafrm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#dialog").html(data);
if($("#senditornot").prop("checked") === false ) {
$("#dialog").attr("title","This dialog box will automatically close.");
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
},
error :function() {
$("#dialog").html(data);
$("#dialog").attr("title","This dialog box will automatically close.");
if($("#senditornot").prop("checked") === false ) {
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
}
});
}
$("#preview").click(function(){
var previewData = $("#estafrm").serialize();
console.log(previewData);
$("#dialog").html(previewData);
alert(previewData);
})
})
</script>
<body>
<form name="estafrm" id="estafrm">
<div class="container">
<input type="text" name="name" id="name" value=""/>
<input type="checkbox" name="sendit" id="senditornot" />
</div>
<br>
<div class="container">
<div align="center">
<input type="submit" id="submitter" value="Submit" />
<input type="button" name="preview" id="preview" value="preview" />
</div>
</div>
</form>

Show javascript variable in html div

Once a form is submitted my javascript hides one div and shows another:
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
The bottom line is where I'm trying to add some text to the div that is dynamically displayed. However, nothing is displayed in the div. I'd also like to show the variable from another function in the same file.
it's the var e = $("#username").val(); from the code below which I would like to add to the div eventually.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin() {
var e = $("#username").val();
var p = $("#password").val();
if(e != "" && p != "") {
$.ajax({
type: 'POST',
url: 'http://localhost/php/log.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
if (response.success) {
$.mobile.changePage("#loginTest");
}
else {
alert("Your login failed");
}
},
error: function(error){
alert('Could not connect to the database' + error);
}
});
}
else {
alert("You must enter username and password");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
HTML Code:
<body>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="button" value="Login" id="submitButton" onclick="handleLogin()">
<div data-role="footer">
</div>
</div>
<div id="loginTest" data-role="page">
<div id="name">
</div>
</div>
</body>
try this on element id loginTest (#loginTest)
document.getElementById('loginTest').innerHTML= your variable here; //or any string
if you are using jquery
$( '#loginTest' ).text( your variable ); //or any string
Wouldn't you be better to restrict the post back:
<input type="button" value="Login" id="submitButton" onClientClick="handleLogin()">
and then return false from the function.

Categories

Resources