asp and javascript message alert doesn't work - javascript

here's my code
<%
if request.form("Add") = " Add " then
if request.form("txtdistributor") = "" or request.form("sinumber") = "" or request.form("tstdate") = "" or request.form("drnumber") = "" or request.form("drdate") = "" or request.form("receivedby") = "" then
response.redirect("salesinvoice.asp?userloggedin=" &request.querystring("userloggedin") &"&dist=" &request.QueryString("dist") )
end if
SQLString = "INSERT INTO salesinvoice (distributor,sidate,sinumber) VALUES ('" & Request.form("txtdistributor") & "','" & Request.Form("tstdate") & "','" & Request.Form("sinumber") &"') "
set DBConn = Server.CreateObject("ADODB.Connection")
DBConn.Open Application("dals_ConnectionString")
DBConn.Execute(SQLString)
DBConn.Close
set DBConn = Server.CreateObject("ADODB.Connection")
DBConn.Open Application("dals_ConnectionString")
SQLString = "INSERT INTO Delivery_Receipt (Date_Purchase, Receipt_no, Distributor, Received_by, Entry_Date,sinumber) VALUES"
SQLString = SQLString & "('" & Request.Form("drdate") & "','" & Request.Form("drnumber") & "', '" & Request.Form("txtdistributor")& "','" & Request.Form("receivedby") & "','" & now() & "','" & request.Form("sinumber") & "')"
DBConn.Execute(SQLString)
DBConn.Close
response.Redirect("salesinvoice.asp?userloggedin=" &request.QueryString("userloggedin") &"&dist=" &request.QueryString("dist"))
end if
%>
<!-- Javascript -->
<script type="text/javascript">
function validateform()
{
if (document.frm.txtdistributor.value == '')
{
alert('Please input distributor');
document.frm.txtdistributor.focus();
return false;
}
if (document.frm.txtdistributor.value == '')
{
alert('Please input distributor');
document.frm.txtdistributor.focus();
return false;
}
if (document.frm.sinumber.value == '')
{
alert('Please input sales invoice number');
document.frm.sinumber.focus();
return false;
}
if (document.frm.tstdate.value == '')
{
alert('Please input sales invoice date');
document.frm.tstdate.focus();
return false;
}
if (document.frm.drnumber.value == '')
{
alert('Please input Delivery Receipt Number');
document.frm.drnumber.focus();
return false;
}
if (document.frm.drdate.value == '')
{
alert('Please input Delivery Receipt');
document.frm.drdate.focus();
return false;
}
if (document.frm.receivedby.value == '')
{
alert('Please input requestor');
document.frm.receivedby.focus();
return false;
}
return true;
}
</script>
<html>
<head>
<title>Sales Invoice</title>
</head>
<body>
<!--#include file="header.asp"-->
<form name="frm" id="frm" action="salesinvoice.asp?userloggedin=<%=request.QueryString("userloggedin")%>&dist=<%=request.QueryString("dist")%>" method="post" onSubmit="return validateform();">
<link href="css/calendar.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="calendar_date_picker.js"></script>
<script type="text/javascript">
var cdp1 = new CalendarDatePicker();
var props = {
debug : true,
excludeDays : [6,0,1],
excludeDates : ['20081225','20081226','20091225','20091226'],
minimumFutureDate : 5,
formatDate : '%m-%d-%y'
};
var cdp2 = new CalendarDatePicker(props);
props.formatDate = '%d-%m-%y';
var cdp3 = new CalendarDatePicker(props);
cdp3.endYear = cdp3.startYear + 1;
</script>
<table width="900" align="center">
<tr>
<td width="200">Distributor</td>
<td>
<%if request.querystring("dist") <> "yes" then%>
<select name="txtdistributor" style="width:260;">
<option value="">- Select -</option>
<%
strsql = "select Distinct(Distributor) from salesinvoice"
set rsdist = server.createobject("adodb.recordset")
rsdist.open strsql,application("dals_connectionstring")
while not rsdist.eof
%>
<option value="<%=rsdist("distributor")%>"><%=rsdist("distributor")%></option>
<%
rsdist.movenext
wend
rsdist.close
set rsdist = nothing
%>
</select> Add New Distributor
<%end if%>
<%if request.querystring("dist") <> "no" then%>
<input type="text" size="38" name="txtdistributor" id="txtdistributor"> [ - ]
<%end if%>
</td>
</tr>
<tr>
<td>SI Number</td>
<td><input type="text" name="sinumber" id="sinumber"></td>
</tr>
<tr>
<td>SI Date</td>
<td><input type="text" name="tstdate" id="txtdate" readonly> <img src="images/calendar.png" border="0" align="absmiddle" style="cursor:hand;" title="Calendar"></td>
</tr>
<tr>
<td>DR Number</td>
<td><input type="text" name="drnumber" id="drnumber"></td>
</tr>
<tr>
<td>DR date</td>
<td><input type="text" name="drdate" id="drdate" readonly> <img src="images/calendar.png" border="0" align="absmiddle" style="cursor:hand;" title="Calendar"></td>
</tr>
<tr>
<td>Received by</td>
<td>
<!--<input type="text" name="receivedby" id="receivedby">-->
<select name="receivedby" id="receivedby">
<option value="">- Select -</option>
<%
strsql = "select first_name,last_name from sysadusers"
set rsname = server.CreateObject("adodb.recordset")
rsname.open strsql,application("dals_connectionstring")
while not rsname.eof
%>
<option value="<%=rsname("first_name")%>, <%=rsname("last_name")%>"><%=rsname("first_name")%>, <%=rsname("last_name")%></option>
<%
rsname.movenext
wend
rsname.close
%>
</select>

You might have runtime error in the validation function, for example when the form does not contain the txtdistributor drop down.
For the sake of debugging, change the function to this only:
function validateform() {
alert("validation started");
var oDDL = document.frm.txtdistributor;
if (oDDL) {
if (oDDL.value == '') {
alert('Please input distributor');
oDDL.focus();
}
} else {
alert("form does not contain txtdistributor");
}
alert("validation ended");
return false;
}
If this works, apply the same logic for the rest of the fields and remove the debug messages.

Related

mapping data in different tables choice

I'm working on a project on data mapping. Some details are explained in other subject :
Splice data in array
Concerning recovery of select values, I'm using JQuery to stock them in array.
When these values are recovered, I would like according to mapping choice, complete existing table. The problem is that how can I detect number of columns before insertion in database.
This following error returned to me every time :
SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1
Query result :
PDO->prepare('INSERT INTO gestion (firstName,lastName,mail) VALUES
(\'test\',\'jean\',\' marc\',\'marc\')')
var choiceFields = [];
var contentChoiceFields = [];
$('#selectFields').multipleSelect({
filter: true,
onClick: function(view)
{
choiceFields.push(view.value);
var length = choiceFields.length - 1;
if (view.checked === false)
{
choiceFields = jQuery.grep(choiceFields, function(value)
{
return value !== view.value;
});
}
contentChoiceFields = choiceFields;
console.log(contentChoiceFields);
$('.selectChoiceFields').val(contentChoiceFields);
},
onCheckAll: function()
{
/*var contentSelect = "";
$('#selectFields').each(function()
{
contentSelect = $(this).val();
choiceFields.push(contentSelect);
});
contentChoiceFields = contentSelect;*/
choiceFields = []; // delete all previous values
var options = document.querySelector('#selectFields');
for(var i=0;i<options.length;i++)
{
choiceFields.push(options[i].text);
contentChoiceFields = choiceFields;
}
$('.selectChoiceFields').val(contentChoiceFields);
},
onUncheckAll: function()
{
choiceFields = [];
$('.selectChoiceFields').val('');
}
});
$(".mapping").on('click', function(event) {
var data = [];
var mapping = $(this).closest('th').text();
$('th input:checked').each(function(index,element) {
var currentCell = element.parentNode;
$('td:nth-child(' + (currentCell.cellIndex+1) + ')').each(function(i,el) {
if($(el).text().match(/^([a-zA-Z]+)(\d+)([a-zA-Z]+)$/))
{
data.push("'" + $(el).text() + "'");
}
else if($(el).text().match(/^(\d+)/))
{
var value = parseInt($(el).text());
data.push("'" + value + "'");
}
else
{
data.push("'" + $(el).text() + "'");
}
});
});
var content = data;
console.log(content);
$('.choiceData').val(content);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://rawgit.com/wenzhixin/multiple-select/master/multiple-select.js"></script>
<link rel="stylesheet" href="https://rawgit.com/wenzhixin/multiple-select/master/multiple-select.css">
</head>
<body>
<div class="select-box">
<label for="selectFields"><span class="label-FieldChoice">Choice fields</span></label>
<select id="selectFields" multiple="multiple" style="display: none;">
<option value="id">id</option>
<option value="username">username</option>
<option value="username_canonical">username_canonical</option>
<option value="email">email</option>
<option value="email_canonical">email_canonical</option>
<option value="enabled">enabled</option>
<option value="salt">salt</option>
<option value="password">password</option>
<option value="last_login">last_login</option>
<option value="confirmation_token">confirmation_token</option>
<option value="password_requested_at">password_requested_at</option>
<option value="roles">roles</option>
<option value="lastName">lastName</option>
<option value="firstName">firstName</option>
</select>
</div>
<table class="table table-striped table-hover" id="tableContent">
<tbody>
<tr>
<th>lastName<input name="lastName" class="mapping" id="lastName" type="checkbox">
</th>
<th> firstName<input name="firstName" class="mapping" id="firstName" type="checkbox">
</th>
<th> âge<input name="âge" class="mapping" id="âge" type="checkbox">
</th>
<th> phoneNumber<input name="phoneNumber" class="mapping" id="phoneNumber" type="checkbox">
</th>
<th> mail<input name="mail" class="mapping" id="mail" type="checkbox">
</th>
</tr>
<tr>
<td class="mappingContent">test</td>
<td> marc</td>
<td> 21</td>
<td> 0265412369</td>
<td> marc.test#bla.fr</td>
</tr>
<tr>
<td class="mappingContent">jean</td>
<td>marc</td>
<td>28</td>
<td>0692123456</td>
<td>marc.jean#orange.fr</td>
</tr>
</tbody>
</table>
</body>
</html>
if($choiceMapping === "completion")
{
if($session->get('tableChoice') == "user")
{
$password = password_hash('test', PASSWORD_DEFAULT);
$content = $cnx->prepare("INSERT INTO ".$session->get('tableChoice')." "."(".$selectChoiceFields[0].", enabled, password, roles, lastName, firstName) VALUES (".$choiceData.",1, '".$password."', 'a:1:{i:0;s:1:\"0\";}', 'test', 'test')");
$content->execute();
$addFlash = $this->addFlash('success', "Completed recording !");
}
else
{
$content = $cnx->prepare('INSERT INTO '.$session->get('tableChoice').' ('.$selectChoiceFields[0].') VALUES ('.$choiceData.')');
$content->execute();
$addFlash = $this->addFlash('success', "Completed recording !");
}
}
else
{
$content = $cnx->prepare('Truncate '.$session->get('tableChoice'));
$content->execute();
$sql = $cnx->prepare('INSERT INTO '.$session->get('tableChoice').' ('.$selectChoiceFields[0].') VALUES (:choiceData)');
$sql->bindValue(':choiceData', $choiceData);
$sql->execute();
$addFlash = $this->addFlash('success', "Completed recording !");
}
result of $selectChoiceFields :
array(1) { [0]=> string(15) "firstName,lastMail,mail" }
result of $choiceData :
string(30) "'test','jean',' marc','marc'"

How to get variable passed from input box to another page [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to get a variable from hidden INPUT text box to another page. I created a search.asp page, when I search a Form from this page, clicked search button, then view.asp page will open with that specific Form ID. On View.asp page, I created a link to open a new page called view2.asp that keeps the same Form ID. But it didn't work. Can you please help? Thanks.
view.asp code
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Menus Search</title>
</head>
<body>
<style>
table, td, th {
border: 1px solid #ddd;
}
th, td {
padding: 3px;
}
</style>
</head>
<body>
<!--#include file="openConn.asp" -->
<%
SET objRS = Server.CreateObject("ADODB.Recordset")
SET objRS1 = Server.CreateObject("ADODB.Recordset")
SET objRS2 = Server.CreateObject("ADODB.Recordset")
SET objRS3 = Server.CreateObject("ADODB.Recordset")
If Request.Form("FormSource") = "SubmitForm" Then
For j = 1 to Request.Form("txtCount")-1
strReport = Request.Form("Report[" & j &"]")
strValue = split(strReport,"$")
sMenuID = strValue(0)
sCategoryID = strValue(1)
sStatus = strValue(2)
'response.write strReport & "::" & sMenuID & "::" & sCategoryID & "::" & sStatus & "<br>"
'response.end
sFormID = Request.Form("FormID")
sSQL = "INSERT INTO Report (FormID, MenuID, CategoryID, Status) VALUES " &_
"('" & sFormID & "', '" & sMenuID & "', '" & sCategoryID & "', '" & sStatus & "');"
objConn.Execute(sSQL)
Next
End If
%>
<form action="" method="post" id="newMenu" name="frmReport" onsubmit="return validateForm(this)">
<p>
<%
'''' RR added today
nFormID= Request("FormID") ''Request.Form("SearchObj")
response.write "FormID: " & nFormID & "<br>"
sSQL2 = "SELECT * FROM Form WHERE Formid = " & nFormID
''response.write "SQL:::: " & sSQL2 & "<br>"
objRS2.Open sSQL2, objConn
'response.Write sSQL2
Do Until objRS2.EOF
sFormName = objRS2("Form_Name")
%>
<h2><%= objRS2("Form_Name") %></h2>
<p><a href="#" onclick="openview2.asp();"/>Click me</a></p>
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2("FormID") %>"><br />
<%
objRS2.MoveNext
Loop
objRS2.Close
%>
<p>
<table>
<thead bgcolor="#336666" style="color:#FFFFFF">
<tr>
<td>Trainer Name:</td>
<td>Pass</td>
<td>Fail</td>
<td>NA</td>
<td>Not taken</td>
</tr>
</thead>
<%
currMenu = ""
sSQL = "SELECT MenuID, Menu_Name FROM Menu where MENUID in (SELECT MENUID FROM Category where formid=" & nFormID & ")"
objRS.Open sSQL, objConn
i=1
While Not objRS.EOF
nMenuID = objRS("MenuID")
sMenuName = objRS("Menu_Name")
If currMenu <> sMenuName Then
currMenu = sMenuName
%>
<tr>
<th bgcolor="#CCCCCC"><%= sMenuName %></th>
</tr>
<input type="hidden" name="MenuID" value="<%=nMenuID%>">
<%
End If
sSQL3 = "SELECT Categoryid, Category_Name FROM Category WHERE MenuID = " & nMenuID & " and FormID=" & nFormID
Set objRS3 = Server.CreateObject("ADODB.Recordset")
objRS3.Open sSQL3, objConn
While Not objRS3.EOF
nCategoryID = objRS3("Categoryid")
sCategoryName = objRS3("Category_Name")
%>
<tr>
<td><%= sCategoryName %></td>
<input type="hidden" name="CategoryID" value="<%=nCategoryID%>">
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$1"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$2"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$3"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$4"></td>
</tr>
<%
objRS3.MoveNext
i = i + 1
Wend
objRS3.Close
objRS.MoveNext
Wend
objRS.Close
%>
</table>
</p>
<p>
<input type="hidden" name="txtCount" value="<%= i %>">
<input type="button" value="Create Menu" onclick="openwin();" />
<input type="hidden" name="FormSource" value="SubmitForm">
<input type="button" value="View2" onclick="openview2();" />
<input type="submit" value="Update">
Go To Search
</p>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
}
// add other checks here...
return true
}
function getCheckedRadioValue(radio) {
for (var i=0; i < radio.length; i++) {
if (radio[i].checked) return radio[i].value
}
return false
}
function openwin()
{
//alert($('#idFormName').val());
//window.location.href = "Create.asp?FormID=" + $('#idFormName').val();
window.open("Create.asp?FormID=" + $('#idFormName').val(), "Create New Menu", "menubar=0,width=700,height=450");
}
function openView2()
{
alert($('#idFormName').val());
window.open("view2.asp?FormID=" + $('#idFormName').val(), "Create New Menu", "menubar=0,width=700,height=450");
}
</script>
</body>
</html>
view2.asp
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Menus Search</title>
</head>
<body>
<style>
table, td, th {
border: 1px solid #ddd;
}
th, td {
padding: 3px;
}
</style>
</head>
<body>
<!--#include file="openConn.asp" -->
<%
SET objRS = Server.CreateObject("ADODB.Recordset")
SET objRS1 = Server.CreateObject("ADODB.Recordset")
SET objRS2 = Server.CreateObject("ADODB.Recordset")
SET objRS3 = Server.CreateObject("ADODB.Recordset")
If Request("FormID")="" then
iFormID =0
Else
iFormID = Request("FormID") ''Request.Form("FormID")
End If
If Request.Form("FormSource") = "SubmitForm" Then
For j = 1 to Request.Form("txtCount")-1
strReport = Request.Form("Report[" & j &"]")
strValue = split(strReport,"$")
sMenuID = strValue(0)
sCategoryID = strValue(1)
sStatus = strValue(2)
'response.write strReport & "::" & sMenuID & "::" & sCategoryID & "::" & sStatus & "<br>"
'response.end
sFormID = Request.Form("FormID")
sSQL = "INSERT INTO Report (FormID, MenuID, CategoryID, Status) VALUES " &_
"('" & sFormID & "', '" & sMenuID & "', '" & sCategoryID & "', '" & sStatus & "');"
objConn.Execute(sSQL)
Next
End If
%>
<form action="" method="post" id="newMenu" name="frmReport" onsubmit="return validateForm(this)">
<p>
<%
'''' RR added today
nFormID= Request("FormID") ''Request.Form("SearchObj")
response.write "FormID: " & nFormID & "<br>"
sSQL2 = "SELECT * FROM Form WHERE Formid = " & nFormID
''response.write "SQL:::: " & sSQL2 & "<br>"
objRS2.Open sSQL2, objConn
'response.Write sSQL2
Do Until objRS2.EOF
sFormName = objRS2("Form_Name")
%>
<h2><%= objRS2("Form_Name") %></h2>
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2("FormID") %>"><br />
<%
objRS2.MoveNext
Loop
objRS2.Close
%>
<p>
<table>
<thead bgcolor="#336666" style="color:#FFFFFF">
<tr>
<td>Trainer Name:</td>
<td>Pass</td>
<td>Fail</td>
<td>NA</td>
<td>Not taken</td>
</tr>
</thead>
<%
currMenu = ""
sSQL = "SELECT MenuID, Menu_Name FROM Menu where MENUID in (SELECT MENUID FROM Category where formid=" & nFormID & ")"
objRS.Open sSQL, objConn
i=1
While Not objRS.EOF
nMenuID = objRS("MenuID")
sMenuName = objRS("Menu_Name")
If currMenu <> sMenuName Then
currMenu = sMenuName
%>
<tr>
<th bgcolor="#CCCCCC"><%= sMenuName %></th>
</tr>
<input type="hidden" name="MenuID" value="<%=nMenuID%>">
<%
End If
sSQL3 = "SELECT Categoryid, Category_Name FROM Category WHERE MenuID = " & nMenuID & " and FormID=" & nFormID
Set objRS3 = Server.CreateObject("ADODB.Recordset")
objRS3.Open sSQL3, objConn
While Not objRS3.EOF
nCategoryID = objRS3("Categoryid")
sCategoryName = objRS3("Category_Name")
%>
<tr>
<td><%= sCategoryName %></td>
<input type="hidden" name="CategoryID" value="<%=nCategoryID%>">
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$1"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$2"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$3"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$4"></td>
</tr>
<%
objRS3.MoveNext
i = i + 1
Wend
objRS3.Close
objRS.MoveNext
Wend
objRS.Close
%>
</table>
</p>
<p>
<input type="hidden" name="txtCount" value="<%= i %>">
<input type="button" value="Create Menu" onclick="openwin();" />
<input type="hidden" name="FormSource" value="SubmitForm">
<input type="submit" value="Update">
Go To Search
</p>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
}
// add other checks here...
return true
}
function getCheckedRadioValue(radio) {
for (var i=0; i < radio.length; i++) {
if (radio[i].checked) return radio[i].value
}
return false
}
</script>
</body>
</html>
It's hard to understand what you are trying to do.
But as I could understand, you want to open view2.asp and be able to have a value from view.asp there.
As I can see you open view2.asp with this line
<input type="button" value="View2" onclick="openview2();" />
And you want this hidden input
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2('FormID') %>">
If this is what you are trying to do. Then your naming is wrong with the javascript. You probably copied and forgot to change name.
See here, where you try to open view2.asp
function openwin()
{
window.openView2("view2.asp?FormID=" + $('#idFormName').val(), "Create New Menu", "menubar=0,width=700,height=450");
}
You need to change openwin() to openview2()
EDIT:
I just also saw you have this strange code
<a href="#" onclick="openview2.asp();"/>Click me</a>
Which is a link to it self, because you have href="#". But you also trying to call a javascript function with this onclick="openview2.asp();".
You do not have a function called openview2.asp(). And this is not how it works.
If you are trying to call view2.asp with this link and pass the hidden input idFormName. Then it's better if you just do a correct link and pass the ID in the url.
I must say it's a very bad solution, because there is no security here. But the code you provided shows that you are only after a function and ignoring any security aspect.
So change this
<h2><%= objRS2("Form_Name") %></h2>
<p><a href="#" onclick="openview2.asp();"/>Click me</a></p>
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2("FormID") %>"><br />
for this
<h2><%= objRS2("Form_Name") %></h2>
<p><a href="view2.asp?idFormName=<%= objRS2("FormID") %>" />Click me</a></p>
<input type="hidden" id="idFormName" name="FormID" value="<%= objRS2("FormID") %>"><br />
I'm leaving the hidden there in case you refer to this somewhere else in your code.
Good luck and Have a nice day!

Alert message won't work using jquery

I created a form with the code below. There is a problem that I am unable to solve. The problem is the alert message won't work when the submit button is clicked.
$(document).ready(function() {
$("#btn_id").click(function() {
var valid = validate();
var name_order = $("#name").val();
var address_order = $("#address").val();
var city_order = $("#city").val();
var state_order = $("#state").val();
var zipcode_order = $("#zipcode_id").val();
var phone_order = $("#phone_id").val();
var email_order = $("#emailid").val();
var randID_order = $("#generateID").val();
var ICCID_order = $("#ID").val();
if (valid) {
$("form[name='workorder']").submit();
alert(" Name :" + name_order + " \n Address : " + address_order +
" \n City : " + city_order + " \n State: " + state_order +
" \n Zipcode: " + zipcode_order + " \n Phone: " + phone +
" \n Email: " + email_order + " \n ID: " + randID_order +
" \n SIM Card: " + ICCID_order)
}
});
// Give Alert if field not enter
function validate() {
if (document.workorder.name.value == "") {
alert("Please provide your Name!")
document.workorder.name.focus();
return false;
}
if (document.workorder.address.value == "") {
alert("Please provide your Address!")
document.workorder.address.focus();
return false;
}
if (document.workorder.city.value == "") {
alert("Please provide your City!")
document.workorder.city.focus();
return false
}
if (document.workorder.state.value == "-1") {
alert("Please select your State!")
document.workorder.state.focus();
return false
}
if (document.workorder.zipcode.value == " ") {
alert("Please provide your Zipcode!")
document.workorder.zipcode.focus();
return false;
}
if (document.workorder.phone.value == " ") {
alert("Please provide your Phone!")
document.workorder.zipcode.focus();
return false;
}
var email = document.workorder.emailid.value;
atpos = email.indexOf("#")
dotpos = email.lastIndexOf(".")
if (email == " " || atpos < 1 || (dotpos - atpos < 2)) {
alert("Please provide your Zipcode!")
document.workorder.emailid.focus();
return false;
}
console.log("validated");
return (true);
}
// Generate an random ID
function randomString() {
var string_length = 8;
var chars = "abcdefghijklmnopqrstuvwvxyz012345678";
var text = " ";
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
text += chars.substring(rnum, rnum + 1);
}
document.workorder.randomfield.value = text;
}
// Generate box with ID and CCID
function getData() {
var fs = require('fs');
var ICCID = require('./masterlist.json')
if (ICCID.length != 0) {
var index = Math.floor(Math.random() * ICCID.length);
var pickedID = ICCID[index];
ICCID.splice(index, 1); // This removes the picked element from the array
fs.writeFile("masterlist.json", JSON.stringify(ICCID), function(err) {
if (err) {
return consolo.log(err);
}
});
} else {
console.log("Sorry, There is no more ICCID to complete the form");
}
document.workorder.ID.value = pickedID
}
});
<html>
<head>
<title>Work Order Form</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<form action="#" name="workorder" id="form_id">
<table cellpadding="2" width="300" height="300" bgcolor=g reen align="center" cellspaceing="2">
<tr>
<td colspan=2>
<center>
<fontsize=4><b>Work Order Form</b>
</font>
</center>
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" id="name" size="30" align="center">
</td>
</tr>
<tr>
<td>Address</td>
<td>
<input type="text" name="address" id="adress" size="30">
</td>
</tr>
<tr>
<td>City</td>
<td>
<input type="text" name="city" id="city" size="30">
</td>
</tr>
<tr>
<td>State</td>
<td>
<select name="state">
<option value="-1" selected>select..</option>
<option value="Alabam">AL</option>
<option value="Alaska">AK</option>
<option value="Arizona">AZ</option>
<option value="Arkansa">AR</option>
<option value="California">CA</option>
<option value="Colorado">CO</option>
<option value="Connecticut">CT</option>
<option value="Delaware">DE</option>
<option value="Florida">FL</option>
<option value="Georgia">GA</option>
<option value="Hawaii">HI</option>
<option value="Idaho">ID</option>
<option value="Illinois">IL</option>
<option value="Indiana">IN</option>
<option value="Iowa">IA</option>
<option value="Kansas">KS</option>
<option value="Kentucky">KY</option>
<option value="Louisiana">LA</option>
<option value="Maine">ME</option>
<option value="Maryland">MD</option>
<option value="Michigan">MI</option>
<option value="Minnesota">MN</option>
<option value="Mississpi">MS</option>
<option value="Missori">MO</option>
<option value="Montana">MT</option>
<option value="Nebraska">NE</option>
<option value="Nevada">NV</option>
<option value="New Hampshire">NH</option>
<option value="New Jersey">NJ</option>
<option value="New Mexico">NM</option>
<option value="New York">NY</option>
<option value="Nortj Carolina">NC</option>
<option value="North Dakota">ND</option>
<option value="Ohio">OH</option>
<option value="Oklahoma">OK</option>
<option value="Oregon">OR</option>
<option value="Pennsylvania">PA</option>
<option value="Rhode Island">RI</option>
<option value="South Carolina">SC</option>
<option value="South Dakota">SD</option>
<option value="Tennessee">TN</option>
<option value="Texas">TX</option>
<option value="Utah">UT</option>
<option value="Vermont">VT</option>
<option value="Virgina">VA</option>
<option value="Washington">WA</option>
<option value="West Virgina">WV</option>
<option value="Wisconsin">WI</option>
<option value="Wyoming">WY</option>
</select>
</td>
<tr>
<td>Zipcode</td>
<td>
<input type="text" name="zipcode" id="zipcode_id" size="30">
</td>
</tr>
<tr>
<td>Phone</td>
<td>
<input type="text" name="phone" id="phone_id" size="30">
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input type="text" name="email" id="emailid" size="30">
</td>
</tr>
<tr>
<td>
<input type="reset">
</td>
<td>
<button name="sumbit" type="submit" id="btn_id" onlick="randomString(); getData();">Submit</button>
</td>
</tr>
<tr>
<td>
<name="randomfield" id="generateID" value=" ">
</td>
<td>
<name="ID" id="ID" value=" ">
</td>
</tr>
</form>
</table>
</body>
When you sumbit() the form, you leave the page. The alert() never fires! Try changing the code to:
if (valid)
{
alert(" Name :" + name_order + " \n Address : " + address_order +
" \n City : " + city_order + " \n State: " + state_order+
" \n Zipcode: " + zipcode_order + " \n Phone: " + phone +
" \n Email: "+ email_order + " \n ID: " + randID_order +
" \n SIM Card: " + ICCID_order);
$("form[name='workorder']").submit();
}
instead of $(button).click() use $(form).submit for your listener
in your code the form does not have a post location. You can add a return false to the bottom of the submit anonymous function for now
you have a reference to a variable "phone" in your alert call that is not defined
$("form#form_id").submit(function() {
var valid = validate();
var name_order = $("#name").val();
var address_order = $("#address").val();
var city_order = $("#city").val();
var state_order = $("#state").val();
var zipcode_order = $("#zipcode_id").val();
var phone_order = $("#phone_id").val();
var email_order = $("#emailid").val();
var randID_order = $("#generateID").val();
var ICCID_order = $("#ID").val();
if (valid) {
// you don't need to manually submit it since we attached to the submit listener above instead of click
// $("form[name='workorder']").submit();
alert(" Name :" + name_order + " \n Address : " + address_order +
" \n City : " + city_order + " \n State: " + state_order +
" \n Zipcode: " + zipcode_order + " \n Phone: " + phone_order + // you had a bad reference here
" \n Email: " + email_order + " \n ID: " + randID_order +
" \n SIM Card: " + ICCID_order)
}
// return false until you put in a proper post location
return false;
});
I fixed all these in an example at https://jsfiddle.net/algorithmicMoose/n0t83ees/ with comments

Form validation without error on IE

I have a html code saved as a php, the form validation works in google chrome but not in IE. In IE after I hit the submit button, the page automatically goes to process form regardless of errors.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var errors = 0;
var fName = document.forms["orderForm"].firstName.value;//first name validation
if (fName == null || fName == "")
{
document.getElementById('firstNameError').innerHTML = "Please enter a first name.";
errors++;
} else {
document.getElementById('firstNameError').innerHTML = "";
}
//var lName = document.forms["orderForm"].lastName.value;//last name validation
if (lName == null || lName == "")
{
document.getElementById('lastNameError').innerHTML = "Please enter a last name.";
errors++;
} else {
document.getElementById('lastNameError').innerHTML = "";
}
//var address = document.forms["orderForm"].address.value;//address validation
if (address == null || address == "")
{
document.getElementById('addressError').innerHTML = "Please enter an address.";
errors++;
} else {
document.getElementById('addressError').innerHTML = "";
}
//var city = document.forms["orderForm"].city.value;//city validation
if (city == null || city == "")
{
document.getElementById('cityError').innerHTML = "Please enter a city.";
errors++;
} else {
document.getElementById('cityError').innerHTML = "";
}
//var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if (pCodeCheck)
{
document.getElementById('postalCoderror').innerHTML = "";
}
else
{
document.getElementById('postalCoderror').innerHTML = "Please enter a valid postal code.";
errors++;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if (itemQTY < 0)
{
document.getElementById('qtyError').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError').innerHTML = "";
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if (itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError2').innerHTML = "";
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if (itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError3').innerHTML = "";
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if (wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML = "You must order atleast one item.";
errors++;
} else {
document.getElementById('itemQTY').innerHTML = "";
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3);
alert('Your total is: $' + total4 + '.00');
return errors;
}
function startValidate() {
var errors = validateForm();
if (errors == 0) {
document.forms['orderForm'].submit();
} else {
return false;
}
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" action="processForm.html" onsubmit="return startValidate()">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Quebec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
When you look at the console in IE’s developer tools (F12), you will see that there is an error message about undeclared variable lName. This causes the error checking to be aborted.
You have several lines like
//var lName = document.forms["orderForm"].lastName.value;//last name validation
Since // starts a comment in JavaScript, the line has no effect. The variable lName is not declared or defined elsewhere either.
So you need to remove those // comment starters. Note that the code does not work in Chrome either; you may have tested a different version in Chrome, or misinterpreted some behavior.
In the console, you can also see a message for line 237 about “unexpected identifier”. It is actually a serious HTML markup error; IE reports some of such errors, in a strange way. The error is that a tr element has an input element as child, which is forbidden in HTML syntax. This is why the Submit Order and Reset Form appear on top of each other and not on the same row as intended. (For usability, the Reset Form button should be removed, but I digress.)

how to show an alert after validation but before submission

I have all of my validation code figured out but I'm not quite sure on how to code an alert to pop up before the form is submitted but after the validation is complete.
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validate()
{
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
/*
// trying to send alert with the order total.
// not sure how to call it after the validation is done.
var total1;
var total2;
var total3:
var total4;
if(document.getElementById('widget1qty').value == 0)
{
total1 = 0;
}
else(document.getElementById('widget1qty').value != 0)
{
total1 = document.getElementById('widget1qty').value * 5;
}
if(document.getElementById('widget2qty').value == 0)
{
total2 = 0;
}
else(document.getElementById('widget2qty').value != 0)
{
total2 = document.getElementById('widget2qty').value * 15;
}
if(document.getElementById('widget3qty').value == 0)
{
total3 = 0;
}
else(document.getElementById('widget3qty').value != 0)
{
total3 = document.getElementById('widget3qty').value * 25;
}
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
*/
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" onsubmit="validate();" action="processForm.html">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr></tr><tr></tr><tr></tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" id="btnSubmit" onclick="return validate();" value="Submit Order"></td>
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
I just don't know how to code it to pop up after the validation is complete.
In your form, you could put anid = "myForm"and then do this in javascript:
function validateForm() {
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
return;
}
function startValidate(){
validateForm();
document.forms['orderForm'].submit();
}
Edit:
Just add all the other info in the validateForm() function.
I did't seen it because I started my edit before you added the HTML and the other JS.
According to War10ck's post you should change this :
<input type="submit" name="btnSubmit" id="btnSubmit" onsubmit="startValidate()" value="Submit Order">
You can make another function called FireOnSubmit and do something like this:
`
function FireOnSubmit(){
if(validate()==true) alert(""form validated..is being redirected")
else {
alert("invalid form data");
return false;
}
}
`
You can put FireOnSubmit on the onsubmit of the form instead of the validate function.
Also, you will need to return true or false from your validate function.
Instead of all that JavaScript, this should work just as well.
The submit button cannot be clicked until all fields you pick have been filled.
Then a alert pops up with your message.
This Goes In The Head Section
<script>
function checkform()
{
var f = document.forms["testform"].elements;
var cansubmit=true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length==0) cansubmit=false;
}
if (cansubmit)
{
document
.getElementById('submit'
).disabled=false;
}
}
</script>
Here Is The Form. The Submit Button Is Disabled Until All Fields Are Filled.
<form name="testform">
<input type="text" onKeyup="checkform()" placeholder="First Name"required/><br>
<input type="text" onKeyup="checkform()" placeholder="Last Name" required/><br>
<input id="submit" type="submit" disabled="disabled" value="Submit" onclick="alert('Your Alert Here...')"/>
</form>

Categories

Resources