I have built a web app with GAS that send the data on submit to a google spreadsheet.
Sometimes it happens that if I don't update the google spreadsheet manually, the data just entered in the form doesn't appear in the spreadsheet.
Why? Something is missing in the code I need to add?
This is my code.gs:
function doGet(request) {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* #Process Form */
function processForm(formObject) {
var url = "xxx";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([formObject.azienda,
formObject.test,
formObject.field1,
formObject.field2,
formObject.field3]);
}
function sceltaatecoedatiseguenti() {
var sheet = SpreadsheetApp.openById("xxx").getSheetByName("Sheet3");
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A2:D" + lastRow); // Modified
var data = myRange.getValues();
var optionsHTML = "";
for (var i = 0; i < data.length; i+=1) {
optionsHTML += `<option data-values="${data[i][1]};${data[i][2]};${data[i][3]}">${data[i][0]}</option>`; // Modified
};
return optionsHTML;
}
This is my javascript.html:
<script>
// Prevent forms from submitting.
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.processForm(formObject);
document.getElementById("myForm").reset();
}
// Funzione scelta ateco e dati seguenti -prima parte-
function setValues(select) {
const [v1, v2, v3] = select.options[select.selectedIndex].dataset.values.split(";");
document.getElementById("field1").value = v1;
document.getElementById("field2").value = v2;
document.getElementById("field3").value = v3;
}
// Funzione scelta ateco e dati seguenti -seconda parte-
const select = document.getElementById("test");
setValues(select);
select.addEventListener("change", () => setValues(select));
</script>
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<h1>Master Leads</h1>
<div class="form-row">
<div class="form-group col-md-12">
<label for="azienda">Azienda</label>
<input type="text" class="form-control" id="azienda" name="azienda" required="">
</div>
<div class="form-group col-md-12">
<span class="badge badge-primary">Codici Ateco</span>
</div>
<div class="form-group col-md-2">
<label for="test">Ateco 1</label>
<select class="custom-select" name="test" id="test">
<?!= sceltaatecoedatiseguenti(); ?>
</select>
</div>
<div class="form-group col-md-10">
<label for="field1">Sottocategoria</label>
<input type="text" class="form-control" id="field1" name="field1" readonly>
</div>
<div class="form-group col-md-8">
<label for="field2">Divisione</label>
<input type="text" class="form-control" id="field2" name="field2" readonly>
</div>
<div class="form-group col-md-4">
<label for="field3">Sezione</label>
<input type="text" class="form-control" id="field3" name="field3" readonly>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Inserisci in Master Leads</button>
</form>
<div id="output"></div>
</div>
</div>
</div>
</body>
<?!= include('JavaScript'); ?>
</html>
Conclusions after testing with your spreadsheet:
I could reproduce the issue with your spreadsheet
I could reproduce the issue when making a copy of your spreadsheet
The issue does not occur when creating a brand new spreadsheet
Thus, the issue must be related to some setting in your spreadsheet.
You can either create a new spreadsheet from scratch or use the following workaround:
Go to File - > Spreadsheet Settings and change Calculation to On change and every minute.
This seems to solve your problem.
Related
I have made an web app using google script connected to spreadsheet.
all was running well till i tried to put a functionality of sending email notification when user submits a form information
see error code when run log of user clicked function-
TypeError: Cannot read property 'fn' of undefined userClicked #funcs.gs:8
function-js page is below
'function userClicked(userInfo) {
var ss = SpreadsheetApp.openByUrl(url1);
var ws = ss.getSheetByName("SNAGS");
ws.appendRow([userInfo.fn,
userInfo.contact,
userInfo.email,
userInfo.house,
userInfo.snag,
userInfo.query,
new Date()]);
<script>
document.addEventListener('DOMContentLoaded', function()
{
document.getElementById("btn").addEventListener("click",doStuff);
document.getElementById("house").addEventListener("input",getInfo);
var selectBoxes = document.querySelectorAll('select');
M.FormSelect.init(selectBoxes);
google.script.run.withSuccessHandler(populateHouse).getHouse();
}
);
function populateHouse(hous)
{
var autocomplete = document.getElementById('house');
var instances = M.Autocomplete.init(autocomplete, { data: hous });
}
function doStuff()
{
var isValid = document.getElementById("fn").checkValidity();
if(!isValid)
{
M.toast({html: 'Name Required!'});
}
else
{
addRecord();
}
}
function addRecord ()
{
var userInfo = {};
userInfo.fn = document.getElementById("fn").value;
userInfo.contact = document.getElementById("contact").value;
userInfo.email = document.getElementById("email").value;
userInfo.house = document.getElementById("house").value;
userInfo.snag = document.getElementById("snag").value;
userInfo.query = document.getElementById("query").value;
google.script.run.userClicked(userInfo);
document.getElementById("fn").value ="";
document.getElementById("contact").value ="";
document.getElementById("email").value ="";
document.getElementById("house").value ="";
document.getElementById("snag").value ="";
document.getElementById("query").value ="";
M.updateTextFields();
var myApp = document.getElementById("snag");
myApp.selectedIindex = 0;
M.FormSelect.init(myApp);
}
function getInfo ()
{
var HouseInfo = document.getElementById("house").value;
if(HouseInfo.length === 3)
{
google.script.run.withSucceshandler(updateInfo).getData(HouseInfo);
}
}
function updateInfo (infos)
{
document.getElementById("info").value = infos;
M.updateTextFields();
}
</script>
<!DOCTYPE html>
<html>
<head>
<base target="_self">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("page-css"); ?>
</head>
<body>
<div class="container">
<h3>TPM Maintance |Ticketing System</h3>
<br>
<div class="row">
<div class="input-field col s4">
<input placeholder="Your Full Names" id="fn" type="text" class="validate" required >
<label for="fn">Your Name:</label>
</div>
<div class="input-field col s4">
<input id="contact" type="text" class="validate">
<label for="contact"> Your Phone number:</label>
</div>
<div class="input-field col s4">
<input id="email" type="email" class="validate" required>
<label for="email">Email:</label>
</div>
</div>
<div class="row">
<div class="input-field col s4">
<i class="material-icons prefix">home</i>
<input type="text" id="house" class="autocomplete" required>
<label for="house">Location Area/ House Unit# </label>
</div>
<div class="input-field col s4">
<select id="snag" required>
<option disabled selected> Snag Category</option>
<?!= list; ?>
</select>
<label>Snag Type</label>
</div>
<div class="input-field col s4">
<input disabled id="info" type="text" class="validate">
<label for="info">Unit_Info</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="query" class="materialize-textarea"></textarea>
<label for="query">Query Desc:</label>
</div>
</div>
<div class="row">
<button id="btn" class="btn waves-effect waves-light deep-orange darken-2" type="submit" name="action">Send Ticket!
<i class="material-icons right">send</i>
</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include("page-js"); ?>
</body>
</html>
//html part
please see more code from my work thanks. please excuse me im abit a newbie
If you are running the steps from the tutorial video you have tried to run userClicked() function to authorize the Gmail API's. Since Apps Script is thinking that it's a standalone function, userInfo is considered undefined. This is expected behavior.
Excerpt from video:
please let me know why my code didn't work well ?(appscript and html files) , have google spread sheet an access to it , but the code always go to els condition not to if ...
i want when i login check first if found the mail on spreadsheet goto home page if else stay on the login page
script code
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate();
var p = e.parameter;
var sheet = SpreadsheetApp.openById('1EaBfdWqgc927-Syt-H7DwtN7JyYE_VqMBsQs_hnthRg');
var data = sheet.getSheetByName('Teacher Contact Information').getDataRange().getValues();
var iqraEmail= p.email;
for (i in data) {
if (data[i][5] == p && iqraEmail){
Logger.log(iqraEmail);
return HtmlService.createHtmlOutputFromFile('Home').setTitle("Syllabus");
}
else
{
return HtmlService.createHtmlOutputFromFile('Index').setTitle("Login");
}
break;
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<base target="_top">
</head>
<body style="background-image:url('http://drive.google.com/uc?export=view&id=1N8D4M91tqNUgKuEId1p0OKaY1sUpRhrd')">
<form action="https://script.google.com/macros/s/AKfycbxCaNjVg0x-uFT5dD0xH5YgTMADHoMAraRIhna2XWc1-mgKsSI/exec" class="mx-5 mt-5">
<center>
<img class="" style="margin: 8rem 1rem 1rem !important" src="https://iqranetwork.com/wp-content/uploads/2017/03/logo_v2.png" />
<h2>
<strong>IQRA Syllabus</strong>
</h2>
</center>
<div class="form-row">
<div class="form-group col-md-4"></div>
<div class="form-group col-md-4">
<label style="text-align: center" for=""><span class="required"></span><strong>IQRA Email :</strong> </label>
<input class="form-control" type="email" placeholder="---" name="email" id="email" required>
</div>
</div>
<input type="hidden" name="" id="" value="">
<div style="text-align: center">
<button type="submit" id="submit" class="btn btn-danger" onclick="google.script.host.close()"> Login </button>
</div>
</form>
<!-- ==================================================== Form End =================================== -->
</body>
</html>
home.html
<html>
<head>
<base target="_top">
</head>
<body>
<form action="https://script.google.com/macros/s/AKfycbxCaNjVg0x-uFT5dD0xH5YgTMADHoMAraRIhna2XWc1-mgKsSI/exec" class="mx-5 mt-5">
Hello
</form>
</body>
</html> ```
Although I don't get to see your sheet and I am unable to set up appscript now, let me see if I can help from my head. At first, I am assuming that the only wrong portion is the script code. Thus, try this first:
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate();
}
function doPost(e){
var sheet = SpreadsheetApp.openById('1EaBfdWqgc927-Syt-H7DwtN7JyYE_VqMBsQs_hnthRg');
var data = sheet.getSheetByName('Teacher Contact Information').getDataRange().getValues();
var iqraEmail= e.parameter.email;
for (i in data) {
if (data[i][5] == iqraEmail){
Logger.log(iqraEmail);
return HtmlService.createHtmlOutputFromFile('Home').setTitle("Syllabus");
}
}
return HtmlService.createHtmlOutputFromFile('Index').setTitle("Login");
}
I am trying to implement the following behavior.
I have a form and I want to require filling at least one of the check boxes or text field.
I am trying to do this with the following code, but I don't know what am I doing wrong. Thanks in advance.
https://jsfiddle.net/AlexLavriv/mc8fj4f9/
// Code goes here
var app = angular.module('App', []).controller("Ctrl", Ctrl);
function Ctrl($scope) {
$scope.formData = {};
$scope.formData.selectedFruits = {};
$scope.fruits = [{'name':'Apple', 'id':1}, {'name':'Orange', 'id':2}, {'name':'Banana', 'id':3}, {'name':'Mango', 'id':4},];
$scope.someSelected = function (object) {
console.log(object);
for (var i in object)
{
if (object[i]){
return true;
}
}
return false;
}
$scope.submitForm = function() {
console.log($scope.formData.selectedFruits);
}
}
<div ng-controller="Ctrl" >
<form class="Scroller-Container" name="multipleCheckbox" novalidate >
<div ng-app>
<div ng-controller="Ctrl">
<div>
What would you like?
<div ng-repeat="(key, val) in fruits">
<input type="checkbox" ng-model="formData.selectedFruits[val.name]">
{{val.name}}
</div>
<p class="error" ng-show="submitted && multipleCheckbox.$error.required">Select check box or input text</p>
</div>
<pre>{{formData.selectedFruits}}</pre>
<input type="text" ng-required="!someSelected(formData.selectedFruits)" />
<input type="submit" id="submit" value="Submit" ng-click="submitted=true" />
</div>
</div>
</form>
</div>
You can't use ng-required with a function
You can find another solution here: https://jsfiddle.net/mc8fj4f9/2/
var app = angular.module('App', []).controller("Ctrl", Ctrl);
function Ctrl($scope) {
$scope.formData = {};
$scope.formData.selectedFruits = {};
$scope.fruits = [{'name':'Apple', 'id':1}, {'name':'Orange', 'id':2}, {'name':'Banana', 'id':3}, {'name':'Mango', 'id':4},];
$scope.submited=false;
$scope.someSelected = function (object) {
console.log(object);
for (var i in object)
{
if (object[i]){
$scope.checkboxSelected =true;
return true;
}
}
$scope.checkboxSelected =false;
return false;
}
$scope.submitForm = function() {
console.log("submit "+ $scope.formData.selectedFruits);
$scope.submitted=true;
$scope.someSelected($scope.formData.selectedFruits);
}
}
<div ng-controller="Ctrl" >
<form class="Scroller-Container" name="multipleCheckbox" novalidate>
<div ng-app>
<div ng-controller="Ctrl">
<div>
What would you like?
<div ng-repeat="(key, val) in fruits">
<input type="checkbox" ng-model="formData.selectedFruits[val.name]" ng-required = "!inputVal">
{{val.name}}
</div>
<p class="error" ng-show="submitted && !checkboxSelected && !inputVal">Select check box or input text</p>
</div>
<pre>{{formData.selectedFruits}}</pre>
<input type="text" ng-required="!checkboxSelected" ng-model="inputVal"/>
<input type="submit" id="submit" value="Submit" ng-click="submitForm()" />
</div>
</div>
</form>
</div>
I have resorted to using Bootstrap popover because HTML validation exhibits the same behavior I am now experiencing. Perhaps the solution for one will work for both.
JS
var validate = validate || {};
validate.issueError = function ($elem, msg, placement) {
placement = placement == undefined ? 'bottom' : placement;
$elem.attr('data-toggle', 'popover');
$elem.attr("data-offset", "0 25%");
var exclamationPoint = "<span style='font-weight: bold; font-size:medium; color: white; background-color: orange; height: 12px; padding: 1px 6px; margin-right: 8px;'>!</span>";
var content = "<span style='font-size: smaller;'>" + msg + "</span>";
$elem.popover("destroy").popover({
html: true,
placement: placement,
content: exclamationPoint + content
})
$elem.focus();
$elem.popover('show');
setTimeout(function () { $elem.popover('hide') }, 5000);
$elem.on("keydown click", function () {
$(this).popover('hide');
$(this).off("keydown click")
})
}
validate.edits = {
required: function ($form) {
var $reqFlds = $form.contents().find('[required], [data-required]');
$reqFlds.each(function () {
var $this = $(this);
var result = ($this.filter("input, select, textarea").length) ? $this.val() : $this.text();
if (!$.trim(result)) {
validate.issueError($this, "Please fill out this field.");
return false;
}
});
return true;
}
HTML (note I have substituted "required' with "data-required" to force the Bootstrap routines).
<!DOCTYPE html>
<html>
<head>
<title>Writer's Tryst - Writers Form</title>
<link type="text/css" href="css/writers.css" rel="stylesheet" />
<style>
body {padding: 0 20px;}
.limited-offer {
background-color: white;
padding: 3px;
margin-bottom: 12px;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container-fluid">
<img id="img-writers" src="#" alt="images" />
<form id="form-writers" method="post" class="form-horizontal well">
<h1>Writers</h1>
<div class="form-group">
<label for="title" class="col-lg-3 control-label">Title</label>
<div class="col-lg-9">
<input type="text" class="form-control" data-required id="title" name="title" autofocus="true" placeholder="Title" />
</div>
</div>
<div class="form-group">
<label for="form-type" class="col-lg-3 control-label">Type of work</label>
<div class="col-lg-9">
<select class="form-control" data-required id="form-type" name="form-type"></select>
</div>
</div>
<div class="form-group">
<label for="genre" class="control-label col-lg-3">Genre</label>
<div class="col-lg-9">
<select id="genre" name="genre" class="form-control" data-required></select>
</div>
</div>
<div class="form-group">
<label for="nbr-pages" class="control-label col-lg-3">Number Pages</label>
<div class="col-lg-9">
<input type="number" id="nbr-pages" name="nbr-pages" class="form-control" data-required placeholder="Pages" />
</div>
</div>
<div id="tips">The objective of a synopsis or query letter is to entice enablers into requesting your manuscript.
It must be concise and to the point and of course very well written. One page is preferred and no more than 3 pages will be accepted.
Sample Query Letter
</div>
<p id="file-warning" class="thumbnail">Your synopsis/query letter must be a PDF file.
<a target="_blank" href="https://www.freepdfconvert.com/" target="_blank">Free file conversion to PDF.</a>
</p>
<div>
<a id="file-upload" class="btn btn-custom-primary btn-file btn-block text-xs-center" role="button">Choose PDF to Upload
<br/><div id="filename" class="btn-block" style="color: #fff">No file chosen</div>
</a>
<input type="file" id="file2upload" style="display: none">
</div><br/>
<div class="form-group">
<!-- <button type="submit" id="writers-submit" class="btn btn-custom-success btn-block m-t-8">Submit</button>-->
</div>
<div class="limited-offer">For a limited time, writer submissions will cost <span style="color: #f00; font-weight:bold">$15.00</span> to offset screening and editing costs and to promote quality synopsises and query letters. We reserve the right to change this policy without notice.</div>
<!-- <form id="form-paypal" name="form-paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" onsubmit="return ajaxSubmit()">-->
<form id="form-paypal" name="form-paypal" method="post" target="_top">
<input type="submit" class="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="U2LE82Z45PJ54">
<input style="display: block; margin: 0 auto;" id="but-pp" type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="PayPal" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
<input id="userid" name="userid" type="hidden" />
<input id="filesize-limit" name="filesize-limit" type="hidden" value="150000" />
</form>
</div>
<script>
angular.element(document).ready(function () {
showImages($("#form-writers"), $("#img-writers"), "authors", ["blake.jpg", "Melville.jpg", "lewis-carroll.jpg", "stephen-king.jpg", "twain.jpg", "camus.jpg", "nietzsche.jpg", "hesse.jpg"]);
});
$(function () {
populateWritersDropdowns();
$(document).on('change', ':file', function () {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$('#file-upload').on('click', function (e) {
e.preventDefault();
$('#file2upload')[0].click();
});
$("#file2upload").on("change", function () {
var filepath = $('#file2upload')[0].value;
var filename = filepath.substr(filepath.lastIndexOf("\\") + 1);
$("#filename").text(filename)
});
$("#but-pp").on("mousedown", function (e) {
//if (!$("#form-writers").get(0).checkValidity()) return false;
var $ret = validate.edits.required($("#form-writers"));
alert($ret.length);
if ($ret != true) {
$ret.focus();
return false;
}
if (!validate.edits.requireFile($("#filename"))) return false;
if (!fileEdits()) return false;
ajaxSubmit();
function fileEdits() {
var fileSizeLimit = $("#filesize-limit").val();
var file = document.getElementById('file2upload').files[0];
var fileName = file.name;
var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
var fileSize = file.size;
if (fileSize > fileSizeLimit) {
showMessage(0, "Your file-size (" + (Math.round(parseInt(fileSize) / 1000)).toLocaleString() + "kb) exceeds the limit of " + (fileSizeLimit.toLocaleString() / 1000) + "kb");
return false;
} else {
if (fileExt.toLowerCase() != "pdf") {
showMessage(0, "Your synopsis / query letter MUST be a PDF file.");
return false;
};
return true;
}
};
function ajaxSubmit() {
var file_data = $('#file2upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', "upload");
form_data.append('title', $("#title").val());
form_data.append('form-type', $("#form-type").val());
form_data.append('genre', $("#genre").val());
form_data.append('nbr-pages', $("#nbr-pages").val());
form_data.append('account-id', localStorage.getItem("account-id"));
ajax('post', 'php/writers.php', form_data, success, 'Error uploading file:', 'text', false, false, false);
function success(result) {
if (result.indexOf("PDF") == -1) {
showMessage(1, "Your submission will go live and you will be notified after our reviews are complete.");
var data = {};
data['writer-id'] = result;
ajax('post', 'php/paypal-ipn.php', data, listenerStarted);
function listenerStarted(result) {
alert("pp=" + result);
}
} else {
showMessage(0, result);
}
setTimeout(function () {
document.getElementById('form-writers').reset();
$("#filename").text("No file chosen");
}, 5000);
};
};
});
});
</script>
</body>
</html>
I am just a beginner in ASP.NET. Now I have 2 pages: master and child page(content page). On the child page, I create a html form which will be used to submit user's input to the server. I use the asp button to submit those but it just validates user's input by running my javascript. The label at the bottom is used to check if it does postback or not. That always shows "False" even the page refreshes after I click on the submit button. I don't know what I am doing wrong here. Also, I want to show all the information of user in a textbox after they are submitted to the server. Hope you can help me out with clear explanation. Thank you very much.
1/Master Page:
2/Child Page (content page):
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder" Runat="Server">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">Contact <strong>Mon Ami Cafe Restaurant</strong>
</h2>
<hr>
</div>
<div class="col-md-8" id="map-canvas">
<!-- Embedded Google Map using an iframe - to select your location find it on Google maps and paste the link as the iframe src. If you want to use the Google Maps API instead then have at it! -->
<!--iframe width="100%" height="400px" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=14291+S+Euclid+St,+Garden+Grove,+CA+92843&aq=&sll=33.754949,-117.938489&sspn=0.010437,0.021136&ie=UTF8&hq=&hnear=14291+S+Euclid+St,+Garden+Grove,+California+92843&t=m&z=14&ll=33.754949,-117.938489&output=embed"></!--iframe><br /><small>View Larger Map</small-->
</div>
<div class="col-md-4">
<h5>Phone:</h5>
<p><strong>*******</strong>
</p>
<h5>Email:</h5>
<p><strong>*******</strong>
</p>
<h5>Address:</h5>
<p><strong>*******</strong>
</p>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">Contact
</h2>
<hr>
<form name="ContactForm" method="post">
<div class="row" id="ContactForm">
<div class="form-group col-lg-4">
<label>Name</label>
<input type="text" id="NAME" class="form-control">
</div>
<div class="form-group col-lg-4">
<label>Email Address</label>
<input type="text" id="EMAIL" class="form-control">
</div>
<div class="form-group col-lg-4">
<label>Phone Number</label>
<input type="text" id="PHONE" class="form-control">
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
<label>Message</label>
<textarea id="MSG" class="form-control" rows="6"></textarea>
</div>
<div class="form-group col-lg-12">
<input type="hidden" name="save" value="contact">
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validateForm();" Text="Submit"/>
</div>
</div>
</form>
</div>
</div>
</div>
<!--The output information will be here -->
<p><asp:Label id="lbl1" runat="server" /></p>
</asp:Content>
Here is my script #Chia... :
<script>
function validateName() {
var x = document.getElementById("NAME").value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
else
return true;
}
function validateEmail() {
var y = document.getElementById("EMAIL").value;
var atpos = y.indexOf("#");
var dotpos = y.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= y.length) {
alert("Not a valid e-mail address");
return false;
}
else
return true;
}
function validatePhone() {
var formatForm = /^[1-9]\d{9}$/;
var z = document.getElementById("PHONE").value;
if (z.length == 0) {
alert("Phone must be filled out");
return false;
}
else if (z.length < 10 || z.length > 10 || !(z.match(formatForm))) {
alert("Not a valid phone number");
return false;
}
else
return true;
}
function validateMess() {
var t = document.getElementById("MSG").value;
if (t == null || t == "") {
alert("Pleave leave your message");
return false;
}
else
return true;
}
function validateForm() {
if (validateName()) {
if (validateEmail()) {
if (validatePhone()) {
if (validateMess()) {
//alert("Submitted Sucessfully");
return true;
}
}
}
}
return false;
}
</script>
You need to add an onclick attribute to your asp button which calls an event in your code behind class. For example
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validateForm();" OnClick="btnSubmit_Click" Text="Submit"/>
Which would trigger the event
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
// Do stuff here after postback
}
Because you have wired up your onclientclick attribute and ValidateForm is returning a bool value, then this will correctly only allow the onclick event to fire if the validateForm function returns true.