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.
Related
I'm trying to create a form where, if the user selects 'yes' from a dropdown, two extra fields appear. Both of these fields are required, and one of them needs to be validated according to an array of 'codes' - the user must input one of the codes in the array for the form to submit correctly. However, if the user selects 'no' from the dropdown, these fields do not appear and are not required, and the array validation does not occur and the form can be submitted.
I have some code for this, however I can't get the fields to appear. An earlier issue I encountered with this (minus the array validation - including that broke the code and stopped the extra fields appearing) was that if the user selected 'yes', and then went back to change their mind and selected 'no', then the form would not submit, clearly still requiring the fields to be filled in/correct array value inputted.
If anyone could help me in making this work I would greatly appreciate it.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
$(document).ready(function() {
checkIfYes = function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
});
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
});
JSFiddle
It's a glitch in the way you define the function -- by calling checkIfYes() it's looking for it on the global (window's) scope. By changing the line:
function checkIfYes() {...
to this:
checkIfYes = function() {...
then you've got it on the global scope. Which is, by the way, bad practice. You'd be better to create a click handler in your script itself, than to hard- code the function call in your HTML. But that's just me.
A few changes made, some pretty significant -- first, I removed the hard-coded reference to checkIfYes and simply put the event in your javascript. Second (and pretty darn significant), I moved the event handlers to the root of your javascript, rather than defining them in your checkIfYes function. This way, they don't depend on that being called each time. Try it, it works.
$(document).ready(function() {
/**
* Define some custom events to handle...
**/
$("#defect").on("change", checkIfYes );
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
console.log("Input is wrong!");
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
e.preventDefault();
console.log("This is where I would be checking...");
if (ValidateInput()) {
$("#auth_form").submit();
}
});
// Utility Functions.
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
I guess I'm doing a trivial error somewhere but will be grateful if someone can spot it.
I am trying to validate a postcode in a form field once it has been typed in. Similar code works fine in PHP but I've spent hours and the JS does not seem to be executing whatever I do.
Here is part of the form (all within body tags):
<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
...
<script type="text/javascript" src="common.js">
</script>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onchange="isValidPostcode(this.form)" required />
Here are versions of the javascript (stuffed with alerts just to print out something).
Version 1:
function isValidPostcode(form) {
alert("called");
var p = document.register.postcode.value;
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
Version 2 (is called without a parameter):
function isValidPostcode() {
alert("called");
var p = document.getElementById('postcode').value.replace(/\s/g,'');
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
I tried binding to other events but can't get a single alert out. Even exact reproduction of the examples is not working. Hope someone gives me an idea of what is wrong.
you should replace onchange with keyup and remove quotes from regex :)
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onkeyup="isValidPostcode(this.value)" required />
function isValidPostcode(value) {
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(value)) console.log("OK");
else console.log("This does not look a valid UK postcode...");
}
You should use the keyup event to do that and add the event using JS, not inline it.
postcodeRegEx is a regex, not a string, you need to remove quotes around it.
function isValidPostcode() {
var p = document.getElementById('postcode').value.replace(/\s/g, '');
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
document.getElementById("postcode").addEventListener("keyup", function() {
isValidPostcode();
});
<form name="register" method="post" action="" autocomplete="off">
<input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' required />
</form>
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.
I am trying to combine a data-list with actual links to make a auto-complete search form... Well here is my code:
<form action="#">
<input list="results" type="text" placeholder="Search Me ;)">
</form>
<datalist id="results" onchange="location = this.options[this.selectedIndex].value;">
<option value="Home.html">Home</option>
<option value="Contact.html">Contact</option>
<option value="Sitemap.html">Sitemap</option>
</datalist>
However it does not work.. Any suggestions?
----NEW UPDATE----
Is it possible to assign the form onsubmit or action to the selected value in anyway?
This will work however you don't use a datalist.
Javascript:
function checkInput(searchQuery)
{
if(searchQuery=="Home")
{
window.location = "Home.html";
}
else if(searchQuery == "Contact")
{
window.location = "Contact.html";
}
else if(searchQuery == "Sitemap")
{
window.location = "Sitemap.html";
}
else
{
document.getElementById("search").submit();
}
}
In order to let this work your form should have an id of 'search'.
Edit
Your input a few changes:
<input type="text" placeholder="Search Me ;)" onkeydown="if (event.keyCode == 13) { checkInput(this.value); return false; }"/>
unfortunately you can't embed links into a datalist
eg
<option value="home">Home</option>
The dom simply doesn't work that way.
you would need to build the solution yourself using javascript.
I suggest taking a look at http://www.jqueryui.com they probably have something to help you
A strange one here guys.
I have a form with a number of fields and one submit button. All of the fields are set to disabled at first except the email field.
I have a method which runs and checks the email field for changes. If it changes then all the other fields are enabled. This works perfectly in firefox, chrome and internet explorer 7/8/9 but in 10 it will not work as shown.
In IE10 all the fields which should be disabled are, but the email field which is not greyed out behaves as if its read only and will not allow entry or focus.
I was initially using the .prop() method to change the disabled state but some of the older IE versions has issues with it so I have instead used the attr() and removeAttribute() methods. Any ideas are appreciated.
Solutions added below - Thanks everyone!!
<form id="query_form" class="form-inline" enctype="multipart/form-data" action="" method="post">
<input type="text" class="input-large" placeholder="email" id="email" name="email" value="" />
<input type="text" class="input-small" placeholder="start date" id="sd" name="sd" value="" disabled="disabled"/>
<input type="text" id="ed" class="input-small" placeholder="end date" name="ed" value="" disabled="disabled"/>
<button type="submit" class="btn" id="run_query" name="run_query" disabled="disabled">Run Query</button>
</form>
function check_required_fields(){
var email = $.trim($("#email").val());
if(email.length > 0){
$("#query_form").find(":input").not("#email").each(function() {
$(this).removeAttr('disabled');
});
}else{
$("#query_form").find(":input").not("#email").each(function() {
$(this).attr('disabled', true);
});
}
}
$(document).ready(function(){
var timer;
$("#email").on("change keyup paste", function () {
clearTimeout(timer);
timer = setTimeout(function () {
check_required_fields()
}, 0);
}).triggerHandler('change');
});
Finally one more tidbit of information I'm using Jquery 1.8.3 and am using bootstrap. The console in firebug shows no errors of any kind nor does developer tools in IE10.
Final piece of the puzzle.
In another script I am using the same code with one edit, it operates on two fields. Thus it looks like following:
<form id="query_form" enctype="multipart/form-data" action="" method="post">
<input type="text" class="input-large" placeholder="email" id="email" name="email" value="" />
<select id="qt" name="qt">
<option selected="selected" value="">select query type...</option>
<option value="taxon_group">species group</option>
<option value="site_name">site name</option>
<option value="taxon_name">species name</option>
</select>
<input type="text" id="ed" class="input-large" placeholder="end date" name="ed" value="" disabled="disabled"/>
<button type="submit" class="btn" id="run_query" name="run_query" disabled="disabled">Run Query</button>
</form>
function check_required_fields(){
var email = $.trim($("#email").val());
var query_type = $("#qt").val();
if(email.length > 0 && query_type.length > 0){
$("#query_form").find(":input").not("#email, #qt").each(function() {
$(this).removeAttr('disabled');
});
}else{
$("#query_form").find(":input").not("#email, #qt").each(function() {
$(this).attr('disabled', 'disabled');
});
}
}
$(document).ready(function(){
var timer;
$("#email, #qt").on("change keyup paste", function () {
clearTimeout(timer);
timer = setTimeout(function () {
check_required_fields()
}, 0);
}).triggerHandler('change');
});
Things work well except that the email field looses focus after each key press in IE10. Any ideas why? It does not happen in the other script with the same function applied to just the email field.
Remove the oninput event, looks like interfering with attribute placeholder in IE10. BTW, as you were already binding onkeyup and onchange bound onpaste instead which should give finally quite the same behaviour as oninput used with keyup/change.
You have to delayed a little events in order to make onpaste working and btw to avoid useless multi calls.
DEMO
$(document).ready(function () {
var timer;
$("#email").on("change keyup paste", function () {
clearTimeout(timer);
timer = setTimeout(function () {
check_required_fields()
}, 0);
}).triggerHandler('change');
});
There is an easy way to achieve this if you are open to suggestions.
$(function(){
$("#email").keyup(function(){
if($(this).val().length <= 0){
$(this).siblings().each(function(){
$(this).attr("disabled", true);
});
}
else{
$(this).siblings().each(function(){
$(this).attr("disabled", false);
});
}
});
});
Here is a fiddle: http://jsfiddle.net/6GnUS/10/
You need to call .change after
$(this).prop('disabled', false).change();
I think you need to change
$(this).attr('disabled', true);
to
$(this).attr('disabled');