How can I call c# method from Jquery Ajax in WebForm? - javascript

I am new to the coding and i am trying to call my c# method through jquery ajax because my form action is not allowing my OnClick() event to run, I cannot remove form action because, my form comes from proprietary software and gives form action automatically every time, i tried to change it to default again but that doesn't work. So now I am trying to run my C# code through Jquery Ajax. If you have better way to solve it please suggest.
Your help is appreciated, Thank You in advance
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="HTMLtoPDF.aspx.cs"
Inherits="HTMLtoPDF.HTMLtoPDF" %>
<!DOCTYPE html>
<!--[if IE 9]><html class="lt-ie10" lang="en" > <![endif]-->
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Incomplete Grade Application</title>
</head>
<body>
<form action="xyz.aspx" id="form1" runat="server" method="post" name="form1">
/// Web Form ///
<div class="row">
<div class="col-sm-12">
<label class="control-label" style="margin-top:0px;margin-left:20px">Please use your mouse/finger sign below:</label>
<div id="esignature"></div>
<input type="hidden" id="bitmap" name="bitmap" value="" />
</div>
</div>
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<button type="button" class="btn btn-danger btn-xs" id="clear">Clear Signature</button>
</div>
<div class="col-lg-2 col-lg-offset-6 col-md-2 col-md-offset-6 col-sm-2 col-sm-offset-6 col-xs-2 col-xs-offset-6">
<div class="pull-right">
<input type="submit" class="btn btn-danger" id="reject-button" name="button" value="Reject" />
</div>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<input type="button" ID="submit" class="btn btn-success" value="Approve" />
<button id="hiddenButton" runat="server" onserverclick="btnClick_Click" style="display:none;" ></button>
</div>
</div>
<hr style="background-color:#750D17;height:1px" />
<div class="row">
<div class="col-lg-12">
<input type="text1" class="form-control" id="reject-reason" name="reject-reason">
<p class="help-block">Reject Reasons (if rejected)</p>
</div>
</div>
</div>
</div>
<br />
<br />
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-migrate-1.3.0.js"></script>
<script src="https://workflow.stratford.edu/Content/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src='https://workflow.stratford.edu/Content/jSignature/flashcanvas.js' type='text/javascript'></script>
<![endif]-->
<script src='https://workflow.stratford.edu/Content/jSignature/jSignature.min.js'></script>
<script type="text/javascript">
var isEmpty = function (element) {
if ($("#" + element).val() == "" || $("#" + element).val() == null) {
return true;
} else {
return false;
}
};
var arrayCheck = function (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == false) {
return false;
}
};
return true;
};
function arrayAssign(array, num) {
for (var i = 0; i < num; i++) {
array[i] = false;
};
return array;
};
function validationCheck(array, number, element) {
if (isEmpty(element)) {
$("#" + element).parent(".form-group").addClass("has-error");
array[number] = false;
} else {
$("#" + element).parent(".form-group").removeClass("has-error");
array[number] = true;
}
};
var pass1 = [];
$(document).ready(function () {
if ($.browser.msie) {
if (parseInt($.browser.version) < "9.0") {
alert("Sorry! This form does not support your current IE version, please use Firefox/Google Chrome to submit.");
}
}
var preSig = $('#stu-sig-bit').val();
$('#stu-sig').attr('src', preSig);
var fakeVari = $("#typea").val();
$("#esignature").jSignature({
"background-color": "transparent",
"decor-color": "transparent",
"color": "#1489FF",
});
$("#clear").click(function () {
$("#esignature").jSignature("reset");
});
$("input[type=text]").attr("readonly", true);
$("textarea1").attr("readonly", true);
//$("input[type=radio]").attr("disabled", "disabled");
$("#reject-reason").attr("readonly", false);
$("#submit").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
arrayAssign(pass1, 2);
pass1[2] = false;
validationCheck(pass1, 0, "remaining_work");
validationCheck(pass1, 1, "deadline_date");
pass1[2] = true;
if (!arrayCheck(pass1)) {
return false;
}
else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to approve the case?');
if (answer == true) {
document.getElementById('<%= hiddenButton.ClientID %>').click();
} else {
return false;
}
}
});
$("#reject-button").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
if (isEmpty("reject-reason")) {
alert("Please write down the reason why you reject the request.");
return false;
} else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to reject the case?');
if (answer == true) {
} else {
return false;
}
}
});
});
</script>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Click(object sender, EventArgs e)
{
DownloadAsPDF();
}
public void DownloadAsPDF()
{
try
{
string strHtml = string.Empty;
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "CASEID6.pdf";
//string testPath = Server.MapPath("~/files/test.pdf");
string template = File.ReadAllText(Server.MapPath("~/Incomplete-Pdf-temp.html"));
CreatePDFFromHTMLFile(template, pdfFileName);
Response.Redirect("SendEmail.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
GeneratePDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
reader.Close();
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
File.Copy(ModifiedFileName, FinalFileName);
if (File.Exists(ModifiedFileName))
File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
}
}

You would implement a web-service, or you would utilize a handler file. This generic handler is often used, since it doesn't require a form. Once you utilize the template you'll have a file that should appear as follows:
public class SampleHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
}
public bool IsReusable
{
get { return false; }
}
}
From your primary application, or form, you would execute your ajax as follows:
<script type="text/javascript">
$.ajax({
url: '<% Page.ResolveUrl("/SampleHandler.ashx") %>',
method: 'post',
...,
success : function (response) {
// Handle .ashx response.
}
});
</script>
That is one of the simplest approaches. As it will allow you to separate your logic, compared to the declaration of a method in your code behind decorated in a [WebMethod] attribute.

Related

Can't find the variable "SSL" javascript

ERROR: Can't find variable SSL
Good morning, I was finishing the script when I find a problem that I couldn't solve. When I click on a button, it tells me can't find the variable "SSL" but it is created (just show the error when I click one button), can you tell me if there are some misstake?
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = ss =function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.name.push(url.trim());
el.value = '';
this.FetchAll();
}
if (url) {
MyJSON.url.push(url1.trim());
el1.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.urls.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.name.splice(item, 1);
this.FetchAll();
};
}
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
}
Solved, the variable SSL was into start so, it wasn't global variable.
I needed to do window.SSL = SSL and It works.
Thanks you CertainPerformance and #Chriag Ravindra

Can't retrieve RadDatePicker object from Javascript

I'm pulling my hair over this, I can't get the Client-Side API of RadDatePicker to work. The object has no function or no properties.My want is simple just want to create a object of a RadDatePicker on javascript.please check the ClearControl function.just want to use set_selectedDate method on find datepicker control object.like:
var today = new Date();
var dateAcc = $find("<%=dtpDODate.ClientID %>");
dateAcc.set_selectedDate(today);
Can you help me to find what is wrong with this code on a blank aspx page?
<script type="text/javascript" language="javascript">
function ClearControl(DivID) {
try {
var elements = null;
if (DivID == null) {
var oForm = document.forms['frmSiteMain'];
if (!oForm) {
oForm = document.form1;
}
elements = oForm.elements;
}
else {
elements = document.getElementById(DivID).getElementsByTagName("input");
}
// oForm.reset();
for (i = 0; i < elements.length; i++) {
if (elements[i].type != null) {
field_type = elements[i].type.toLowerCase();
if (field_type) {
if ((elements[i].id.toString().search("body_") == 0 || elements[i].id.toString().search("ctl00_body_") == 0) && elements[i].id.toString().indexOf("_dtp") > 0) {
var today = new Date();
var control = $find(elements[i].id.toString());
control.set_selectedDate(today);
break;
}
}
}
}
}
catch (e) {
alert(e.message + " Type:" + field_type);
}
}
</script>
<div class="p_div" id="divDODate" runat="server">
<div class="m1">
<asp:Label ID="lblDODate" runat="server" Text="Date"></asp:Label>
<telerik:RadDatePicker ID="dtpDODate" runat="server" MapColumnName="strDODate">
<DateInput ID="DateInput1" DateFormat="MM/dd/yyyy" runat="server">
</DateInput>
</telerik:RadDatePicker>
</div>
</div>
Thanks for your assistance,
The problem is specific , wrong object creation syntax,check the bellow sytax
else if ((elements[i].id.toString().search("body_") == 0 || elements[i].id.toString().search("ctl00_body_") == 0) && elements[i].id.toString().indexOf("_dtp") > 0) {
var today = new Date();//get date
var control = $find(elements[i].id.toString());//create object of date picker control
control.set_selectedDate(today);//fill picker with date.
break;
}

Array value not accesible in another function in javascript

I am developing a simple address book. I am using four different arrays to store name,phone no ,address and email of user.When I am calling add() method its adding values to these arrays,but when I am calling display the details its showing address book empty and all these arrays empty. Thanks in advance please help..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="addressBook.css" />
<script src="jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
add();
});
$('#delete').click(function () {
remove_con();
});
$('#view').click(function () {
display();
});
});
</script>
<script type="text/javascript">
var BOOK = new Array();
var BOOKNO = new Array();
var ADDR = new Array();
var EMAIL = new Array();
function add() {
//Take values from text fields
var conname = document.getElementById('userNam').value;
var lenname = BOOK.length;
var x = BOOK.indexOf(conname);
var conno = document.getElementById('userNo').value;
var lenno = BOOKNO.length;
var y = BOOKNO.indexOf(conno);
var conaddr = document.getElementById('userAdd').value;
var lenaddr = ADDR.length;
var z = ADDR.indexOf(conaddr);
var conemail = document.getElementById('userEmail').value;
var lenemail = EMAIL.length;
var w = EMAIL.indexOf(conemail);
//Validations
if (conname.length == 0) {
alert("Name field cannot be blank");
return;
}
else if (conno.length == 0) {
alert("Phone number field cannot be Left blank");
return;
}
else if (conno.length != 10) {
alert("Enter a Valid Phone Number");
return;
}
else if (conaddr.length == 0) {
alert("Address field cannot be blank");
return;
}
else if (conemail.length == 0) {
alert("Email field cannot be blank");
return;
}
//RegEX
alphaExp = /^[a-zA-Z]+$/;
numExp = /^[0-9]+$/;
betaExp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!conname.match(alphaExp)) {
alert("Please enter alphabets only");
return;
}
else if (!conno.match(numExp)) {
alert("Please enter numerals only");
return;
}
else if (!conemail.match(betaExp)) {
alert("Please enter a valid email");
return;
}
else if (y >= 0) {
alert("Phone number already Present");
return;
}
else {
BOOK[lenname] = conname;
BOOKNO[lenno] = conno;
ADDR[lenaddr] = conaddr;
EMAIL[lenemail] = conemail;
var l = BOOK.length;
alert("Contact " + conname + " Added Sucesfully!!!!" +l);
return BOOK,BOOKNO,ADDR,EMAIL;
}
}
function display() {
//document.getElementById('hiddenDiv').style.display = "block";
BOOK = BOOK.sort();
var l = BOOK.length;
alert(l);
var view = "";
if (l == 0) {
document.getElementById('hiddenDiv').innerHTML = "ADDRESS BOOK EMPTY!!!";
}
if (l >= 1) {
view = view + "<table border=1px><tr><td><B>NAME</B></td><td><B>PHONE NUMBER</B></td><td><B>ADDRESS</B></td><td><B>EMAIL</B></td>";
for (var i = 0; i < BOOK.length; i++) {
view = view + "<tr><td>" + BOOK[i] + "</td><td>" + BOOKNO[i] + "</td><td>" + ADDR[i] + "</td><td>" + EMAIL[i] + "</td></tr>";
}
document.getElementById('hiddenDiv').innerHTML = view + "</table>";
}
}
function remove_con() {
var remname = prompt("Enter the name to be removed");
var remlen = BOOK.LENGTH;
/*var remnam=document.getElementById('name').value;
var remno=document.getElementById('phno').value;*/
var z = BOOK.indexOf(remname);
var z1 = z;
var z2 = z;
var z3 = z;
if (remlen == 0) {
alert("ADDRESS BOOK IS EMPTY");
return;
}
if (z >= 0) {
BOOK.splice(z, 1);
BOOKNO.splice(z1, 1);
ADDR.splice(z2, 1);
EMAIL.splice(z3, 1);
alert("Contact deleted");
}
if (z == -1) {
alert("Contact not present");
}
}
function searchcon() {
var lenn1 = BOOK.length;
if (lenn1 == 0) {
alert("ADDRESS BOOK EMPTY");
return;
}
var coname = prompt("Enter name");
var ind = BOOK.indexOf(coname);
if (ind >= 0) {
alert("contact found");
return;
}
else {
alert("Contact not present in address book");
}
}
</script>
</head>
<body>
<div id="mainDiv">
<header id="startHeader">
<p id="headerPara">Welcome to Address Book</p>
</header>
<div id="midDiv">
<form id="submissionForm">
<div class="entryDiv">
<p class="inputType">Name:</p>
<input id="userNam" type="text" class="buttonsClass" placeholder="Enter Your Name" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Number:</p>
<input id="userNo" type="text" class="buttonsClass" placeholder="Enter Your Number" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Address:</p>
<input id="userAdd" type="text" class="buttonsClass" placeholder="Enter Your Address" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Email:</p>
<input id="userEmail" type="email" class="buttonsClass" placeholder="Enter Your Email" required="" />
</div>
<div id="Buttons">
<input id="reset" type="reset" value="Reset" />
<input id="delete" type="button" value="Delete Contact" />
<input id="view" type="button" value="View Book" />
<input id="add" type="submit" value="AddToContacts" />
</div>
</form>
<div id="hiddenDiv">
</div>
</div>
</div>
</body>
</html>
Change add button's type "submit" to "button" then remove return statement from add function as it is not needed.
This code has many issues.
You don't need four array to store address detail. you can make one array that can have objects containing the address information.eg.
var Address=function(name,address,email,mobile){
this.name=name;
this.address=address||"not available";
this.email=email||"not available";
this.mobile=mobile;
}
var AddressBook=new Array();
//Adding data in address book
AddressBook.push(new Address("jhon","baker street","a#in.com","049372497"))
You can use jquery to get value of element instead of pure javascript. eg.
var conname = document.getElementById('userNam').value;
//instead of this use jquery
var conname=$("#userNam").val(); // recommended approach
There is no need to calculate array length everywhere.To check duplicate mobile number you can write a function.
there are many other improvement you can have in code. for more examples go through Jquery site and Github public repositories.
Fiddle Demo
Change the <input id="add" type="submit" value="AddToContacts" /> to type="button". type="submit" will refresh the page to form's action and will reset all variables including BOOK.

How to check for links in textbox JavaScript [duplicate]

This question already has answers here:
How to look for a word in textbox in JavaScript
(3 answers)
Closed 8 years ago.
If there is a link in a textbox then JavaScript will redirect the user to the link when they press a button. For example if the textbox has www.google.com in it the JavaScript would see the "www." and it would play a function which redirects the user to the link entered. Here is my code:
JavaScript:
function showAlert() {
var txtCtrl = document.getElementById("textbox1");
var txtVal = txtCtrl.value;
var txtValUpper = txtVal.toUpperCase();
var txtValLower = txtVal.toLowerCase();
if (txtVal == '') {
alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
} else if (txtValUpper == 'start' || txtValLower == 'start') {
alert('Hello. What would you like me to do?');
} else if (txtValUpper.indexOf("weather") != -1 || txtValLower.indexOf("weather") != -1) {
window.location = "https://www.google.com/#q=weather";
} else if (txtValUpper.indexOf("time") != -1 || txtValLower.indexOf("time") != -1) {
alert('The current time according to your computer is' + formatTime(new Date()));
} else if (txtValUpper.indexOf("help") != -1 || txtValLower.indexOf("help") != -1) {
window.location = "help/index.html";
} else if (txtValUpper.indexOf("donate") != -1 || txtValLower.indexOf("donate") != -1) {
window.location = "donate/index.html";
} else {
alert('Sorry, I do not reconise that command. For a list of commands, type "Help" into the text box.');
}
}
//Show time in 24hour format
function showTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
return [h, m].join(':')
}
//Show time in 12hour format
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
}
return formatted;
}
})();
And HTML:
<!doctype html>
<html>
<head>
<title>Random Project</title>
</head>
<body>
<div class="container">
<img class="logo" src="logo.png" width="450" height="110" alt="Random Project">
<input type="text" name="textbox1" value="" spellcheck="false" dir="ltr" placeholder="Type here" id="textbox1"><br>
<button id="button1" name="button1" aria-label="Help me" onClick="showAlert();">
<span id="button1_text">Help me</span>
</button>
<div class="separator"></div>
<span class="information">© Copyright DemDevs 2013. All rights reserved. Made by Omar Latreche<br>Donate now</span>
<div class="tip">
<span class="tip">Tip: </span><span class="tip_text">The commands are NOT case sensitive</span>
</div>
<div class="example">
<span class="example">Example: </span><span class="tip_text">Show me the weather or What is the current time</span>
</div>
</div>
<div class=""></div>
</body>
</html>
Any help will be greatly appreciated.
Thanks, Omar!
Use pattern matching for this:
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = 'www.google.com'; // you would change this to dynamically check text input
if(t.match(regex))
{
// Execute your code
}

jQuery autoruns functions on change events when page is loaded

I have made a function that validates inputs with for different kind of strings. I am having serious issues with a few things. I call it on form submit and for each input on change. I have written my code below and then the calling of function. Thing is: when I call it on change and refresh the page, it automatically runs the validations on change when the page is loading and renders the errors.
var Val = {
'string': function(ident, req, regexp, offset, limit) {
var ele = $(document.getElementById(ident));
Val.errors = false;
if (!ele.val() && req == 1) {
alert('blank');
Val.errors = true;
$("#" + ident + "Error").html("This field cannot be empty.");
$("#" + ident + "Error").show("fast");
}else if ((ele.val().length <= offset || ele.val().length > limit) && Val.errors == false) {
alert('not long enough');
Val.errors = true;
$("#" + ident + "Error").html("This field must be between " + offset + " & " + limit + " charecters long");
$("#" + ident + "Error").show("fast");
}else if (regexp !== null) {
switch (regexp) {
case 'text':
var regEx = /^([a-zA-Z]+)$/g;
break;
case 'number':
var regEx = /^([0-9]+)$/g;
break;
case 'email':
var regEx = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/g;
break;
case 'date':
var regEx = /^([123]0|[012][1-9]|31)-(0[1-9]|1[012])-(19[0-9]{2}|2[0-9]{3})$/g;
break;
case 'alphanum':
var regEx = /^([a-zA-Z0-9_\-\.]+)$/g;
break;
default:
break;
}
if (!regEx.test(ele.val()) && Val.errors == false) {
alert('not valid');
Val.errors = true;
$("#" + ident + "Error").html("This field is not valid");
$("#" + ident + "Error").show("fast");
}
}
if (!Val.errors){
$("#" + ident + "Error").hide("fast");
}
},
'send': function() {
if (!Val.errors) {
$('#form').submit();
}
}
}
Calling of the function:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Validations</title>
<script type="text/javascript" language="JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript" src="js/gcui.lsat.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#send').click(function(){
checkEmail();
checkUsername();
Val.send();
});
$('#emailID').change(checkEmail());
$('#username').change(checkUsername());
function checkEmail(){
Val.string('email', 1, 'username', 10, 100);
}
function checkUsername(){
Val.string('username', 1, 'alphanum', 5, 15);
}
});
</script>
</head>
<body>
<form id="form" action="">
<input type="text" id="email" name="email" title="Email" />
<input type="text" id="username" name="username" title="Username" />
<input type="button" id="send" value="Submit" />
</form>
Email: <div id="emailError"></div><br/>
Username: <div id="usernameError"></div>
</body>
</html>
$('#emailID').change(checkEmail());
Means "Run checkEmail and pass the return value to the change method"
You want:
$('#emailID').change(checkEmail);
Meaning "Pass the checkEmail function to the change method"
In your $('#send').click(function(){ you do submit it two times. The first time when you do the validation and the second time when the button press is fired. Add the line Return False; just after the Val.send(); and you only get the forum to submit if there form are filled out correct

Categories

Resources