I'm using a GAS to embed a form in a sidebar in a google spreadsheet.
How do I close this sidebar after the form has been submitted and confirmed by the user?
The validation is done before sending the data to the server. After that, the user has to confirm he wants to submit the form with a Yes/No alert box.
If he clicks yes:
The sidebar closes and the data is submitted
If he clicks no:
The sidebar remains open and nothing happens.
In code.gs:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Test')
.addItem('New Test', 'showSidebar')
.addToUi()
}
function include (file) {
return HtmlService.createTemplateFromFile(file).evaluate().getContent();
}
function showSidebar() {
var html = HtmlService.createTemplateFromFile('Page')
.evaluate()
.setTitle('Sidebar')
.setWidth(200);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function processF(form){
var ui = SpreadsheetApp.getUi();
var result = ui.alert(
'Please confirm',
ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
Browser.msgBox('Yes');
return true;
} else{
return false;
//throw new Error( "Optional message" );
}
}
In html:
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script>
function validar(){
try{
var form=document.getElementById('configs');
if(!document.getElementById('nome').value || !document.getElementById('datepicker').value){
return false;
} else {
this.disabled=true;
google.script.run
//.withFailureHandler(google.script.host.close)
.withSuccessHandler(function(closeTF){
if(closeTF==true){
google.script.host.close();
}
}).processF(form);
//google.script.host.close();
}
} catch(e){
alert('Erro: '+e.message);
}
};
</script>
<div class="painel">
<form id="configs" action="#">
<fieldset>
<label>Name</label>
<p><input type="text" name="nome" id="nome" minlength="2" required/></p>
<label>1-Choose date:</label>
<p><input type="text" name="datepicker" id="datepicker" required/></p>
<label>2-Choose:</label>
<p>
<select name="horizonte" id="horizonte">
<option value=1>1 Month</option>
<option value=2>2 Months</option>
<option value=3 selected="selected">3 Months</option>
<option value=6>6 Months</option>
</select>
</p>
<label>3-Choose:</label>
<p>
<select name="relatorio" id="relatorio">
<option value=1>Week</option>
<option value=2>Month</option>
</select>
</p>
<p>
<input type="submit" id="enviar" value="Submit" onclick="validar()" />
</p>
</fieldset>
</form>
</div>
<?!= include('Javascript'); ?>
With this code, the sidebar is always closed, no matter if the user clicks Yes or No.
Updated answer
Thanks for the rest of the code, #NunoNogueira. I've spent considerable time experimenting with it, and I'm confident that the problem is with the use of the alert. This might be related to Issue 4428, but I can't be sure. It's likely that the alert is overriding some window context information. What is clear is that the server is returning undefined to the successHandler, so it's useless on the client side. My recommendation is to abandon use of alert for this work flow.
If you insist on having a confirmation before validating the form, you can use a confirm() on the client:
function validar(){
if (!confirm("Por favor, confirme")) return;
...
Original answer - correct information, but not what the problem was.
The call to return false will trigger the successHandler, because it is a return.
To invoke a failureHandler instead, the server function must FAIL. Instead of a return:
throw new Error( "Optional message" );
... then add a failureHandler in your HTML code.
Related
I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" action="" METHOD="POST">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit" name="submit" onClick="myFunction()"/>
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as 'script type="text/javascript" src="script.js':
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
}
};
When I fill out the form and hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.
How do I make it so that the insertion of HEADING remains permanent?
Move the listener to the form's submit handler. Have the function return false to stop submission:
<form id="date_form" onsubmit="return myFunction();" ...>
Take the listener off the button:
<input type="submit">
Do not give it a name of submit as that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.
There is an error in your code, it's missing a closing double qoute:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false; // to stop submission
};
This may or may not fix you issues, you haven't said what you are actually trying to do.
I'm working on a project. I'm trying to make my code so that when a user submits an option from a dropdown menu, if the user selects and submits the default ("Select a genre"), the form is not submitted and the page is not refreshed. Following is my Javascript code:
<script>
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
</script
This is nested inside a head tag.
Following is my HTML code for the form:
<div>
<form method="POST">
<select id="dropdown" name="genre">
<option value="nothing">Select a genre</option>
<option value="rock">Rock</option>
</select>
<br/>
<br/>
<input id="submit" type="submit"/>
</form>
</div>
The javascript doesn't seem to work, since even when I submit the form while selecting the "Select a genre" option, my form is still submitted, and the python code does work on the value 'nothing', which gives errors.
EDIT: Upon adding further functionality to my project by adding more javascript code, the javascript code again didn't work. I used google chrome's developer tools and stumbled upon this error which seems to be related to why the code isn't working:
Uncaught TypeError: $(...).addEventListener is not a function
at (index):18
Try event.preventDefault():
var menu = document.getElementById("submit");
menu.addEventListener("click", function(event) {
if (document.getElementById("dropdown").value == 'nothing')
{
event.preventDefault();
}
});
<div>
<form method="POST">
<select id="dropdown" name="genre">
<option value="nothing">Select a genre</option>
<option value="rock">Rock</option>
</select>
<br/>
<br/>
<input id="submit" type="submit"/>
</form>
</div>
It is just a declaration of Code if you don't bind to $( document ).ready() or make it as self-invoking function.
First solution:
$( document ).ready(functino(){
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
});
Another Solution:
(function(){
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
}());
My question is a continuation of this post https://stackoverflow.com/questions/22438863/javascript-jquery-for-before-leaving-the-page?noredirect=1#comment34138272_22438863, it's a new function.
Am looking for below function:
In stackoverflow, if you type some answers and if you try to close that tab it will ask for confirmation message..
Below is my Html part:
<form id="demo">
<input type="text" id="name" name=""/>
<input type="email" id="emails" name=""/>
<input type="number" id="ph" name=""/>
<select name="" id="sample">
<option>Select</option>
<option value="1">Chennai</option>
<option value="2">Hyderabad</option>
</select>
</form>
If user enters something and he clicks on logo to navigate away it asks for confirm message..its natural right???Even stackoerflow has this function..I tried this code but didn't worked
var changesMade = false;
function onDataChanged() {
changesMade = true;
}
$('input:text, textarea, select').change(onDataChanged);
$('input:checkbox, input:radio').click(onDataChanged);
$("#homeicon").click(function() {
if (changesMade) {
return 'Changes have been made. Are you sure you want to leave the page?';
location.href = "home.html";
} else {
return null;
}
});
You are looking for onbeforeunload or beforeunload in jQuery.
check here as well as googling for other places with that term.
I have the following code that checks to see that two select fields are identical. The code works alright when called with onsubmit. However after doing this validation the form is still submitted. How can i prevent the script or my form from submitting the incorrect data.
Please see code below:
var fieldalias="Email address field"
function verify(element1, element2) {
var passed=false
if (element1.value=='') {
alert("Please fill out the "+fieldalias+"!")
element1.focus()
}
else if (element2.value=='') {
alert("Please verify the "+fieldalias+"!")
element2.focus()
}
else if (element1.value!=element2.value) {
alert("The two "+fieldalias+"s do not match")
element1.select()
}
else
passed=true
return passed
}
You didn't include your HTML, so I'm going to assume you've added onsubmit() to your form element.
If so, make sure your call looks like this:
onsubmit="return verify(element1, element2)"
(replace element1 and element2 accordingly)
If this assumption is not correct, please include some additional detail so we can better assist.
Try calling stopImmediatePropagation() on the event to prevent any further processing of the submit event by any other handlers in the form element or higher level elements.
Call that code with different event, like i.e: onchange, or onfocusout. This way the validation will be performed every time user enter some values to your fields, certainly before submitting.
EDIT:
I'm not sure if I understand you correctly but I would have attached your JS code this way:
First assign your select box to the variable:
var object_input = document.getElementById("selectId");
And then:
if(object_input.addEventListener)
{
object_input.addEventListener('blur', focus_lost);
object_input.addEventListener('keypress', checkForEnter);
}
else
{
object_input.attachEvent('onblur', focus_lost);
object_input.attachEvent('onkeypress', checkForEnter);
}
and then perform your validation ith focus_lost or checkForEnter.
Assuming that in the html code you have something like this:
<form action="test2.html" method="post" onsubmit="return verify(e1, e2);">
<input type="text" name="e1" /><br/>
<input type="text" name="e2" /><br/>
<input type="submit" value="Validate" />
</form>
You have to put in onsubmit event:
return verify(e1, e2);
so you will not go to the submiting page if the data is not valida
EDIT:
I think the problem is the
element1.select()
in the 3rd if, that this select method does not exist for a select object.
You can use a
element1.focus()
The code that will work is:
var fieldalias="Email address field"
function verify(element1, element2){
var passed=false;
if (element1.value==''){
alert("Please fill out the "+fieldalias+"!");
element1.focus();
}
else if (element2.value==''){
alert("Please verify the "+fieldalias+"!");
element2.focus();
}
else if (element1.value!=element2.value){
alert("The two "+fieldalias+"s do not match");
element1.focus();
}
else
passed=true;
return passed;
}
And
<form action="test2.html" method="post" onsubmit="return verify(document.getElementById('e1'), document.getElementById('e2'));">
<select id="e1">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<select id="e2">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<input type="submit" value="Validate" />
</form>
Yup, basically, I am building a web form that need to provide different required form and validation function fallow by selected country.
I am using
<script type="text/javascript" src=" jquery-1.3.2.min.js" charset="utf-8"></script>
<script type="text/javascript" src=" jquery.validate.js" charset="utf-8"></script>
and here is my JS code
<script type="text/javascript" charset="utf-8">
function updatRequreForm (STATE,ZIPCODE) {
$("#frm_verification").validate({
rules: {
'form[country]' : "required",
'form[state]' : {required: STATE},
'form[zip]': {required: ZIPCODE},
},
messages: {
'form[country]' : "This field is required.",
'form[state]' : "This field is required.",
'form[zip]': "This field is required.",
});
};
function setRequreForm () {
var _cs = $('#country_select')[0];
if ('US' != _cs.value)
{
$('#state_star')[0].innerHTML = '';
$('#zip_star')[0].innerHTML = '';
updatRequreForm (false,false);
}
else
{
$('#state_star')[0].innerHTML = '*';
$('#zip_star')[0].innerHTML = '*';
updatRequreForm (true,true);
}
};
$(document).ready(function() {
setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
</script>
Here is my HTML:
<form id="frm_verification" action="some.php" method="POST">
<label for="country_select"><sup>*</sup>Country:</label>
<select name="form[country]" id="country_select">
<option value="">- Select -</option>
<option value="US" selected="selected">United States</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
<label for="select-state"><sup id="state_star">*</sup>State/Province/Region:</label>
<span id="states_select">
<select id="select-state" name="form[state]">
<option value="">- Select -</option>
<option value="AK">Alaska</option>
</select>
</span>
<span id="states_text" style="display:none;">
<input type="text" name="form[state]" value="" id="state" />
</span>
<label for="zip_code"><sup id="zip_star">*</sup>ZIP/Postal Code:</label>
<input type="text" id="zip_code" name="form[zip]" value="" id="zip">
<input type="submit" value="Submit" id="submit_btn" class="submit">
</form>
Basically, what I need to create is:
1.When user select US on country selection, the State and Zip area become required.
2.When user select Zambia on country selection, the State and Zip area become non-required.
Problem:
When I first load the page and click the Submit button with empty field, the form successfully validate each fields and shows warning. However selecting of the Zambia, the validation is not working.
Guess:
I have removed “setRequreForm ();” on ready function like:
$(document).ready(function() {
//setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
And tried to select Zambia, and tried to validate the form and it works. So I think calling “validate()” twice causes error.
Well I stuck with this for a while. Please help me to figure this out, I will really appreciate that.
You can't call validate more than ones becouse you run validate plugin more than one and this lead to errors.
You can setup your validator like this:
$("#myform").validate({
ignore: ".ignore"
})
Ignore tells to validator: field which has ignore css class should not be validated.
When you change requirements then add to specified fields css class "ignore":
$("#field1").addClass("ignore");
otherwise remove this class:
$("#field2").removeClass("ignore");