Solved

How to disable ENTER key in XML created form?

Posted on 2002-05-28
21
385 Views
Last Modified: 2012-06-27
I purchased Teach Yourself ASP in 24 hours and am trying to implement the example in chapter 24 for
a simple shopping bag. I need to modify this example to ignore the ENTER key for the form it creates.

To see the example go to: http://www.asp24h.com/ and click on try the examples on-line (chapter 24) You can also download  the bag.asp page from here.

There are a number of routines in this example - but I'm interested in the one below - which writes my shopping bag items to a form. On my web site I've added a couple of text boxes and a submit button to send the information to me via email - but I REALLY need to disable the ENTER key- as the ENTER key recalculates the form and clears all of the fields.

I'm really new at this - so I need to know EXACTLY  what to change to have the ENTER key ignored and have the buttons on work if the user clicks on them. I've already looked at numerous examples on-line and wasn't able to figure it out.

Here's the procedure that creates the form and writes out the shopping bag:

Sub PrintBag(BagItems)
     Out "<FORM METHOD=""POST"" ACTION="""
     Out Request.ServerVariables("SCRIPT_NAME") & """>"
     Out "<TABLE><TR><TH>Units</TH><TH COLSPAN=2>"
     Out "Product</TH><TH>Unit Price</TH><TH>Price</TH>"
     Out "</TR>" & vbCrLf
     For Each item In BagItems.childNodes
          Out "<TR><TD><input type=""TEXT"" name=""Qty"
          Out item.attributes.getNamedItem("productid")
          Out """ VALUE=""" & item.text & """ SIZE=""3"">"
          Out "<TD>" & item.attributes.getNamedItem("productname")
          Out "</TD><TD>" & item.attributes.getNamedItem("quantityperunit") & "</TD>"
          nUnitPrice = item.attributes.getNamedItem("unitprice")
          nSubTotal = item.text * nUnitPrice
          nTotal = nTotal + nSubTotal
          Out "<TD>" & FormatCurrency(nUnitPrice) & "</TD>"
          Out "<TD><B>" & FormatCurrency(nSubTotal) & "</B></TD>"
          Out "</TR>" & vbCRLF
     Next
     Out "<TR><TD COLSPAN=5><HR></TD></TR>"
     Out "<TR><TD COLSPAN=3></TD><TD><B>Total:</B></TD>"
     Out "<TD><B>" & FormatCurrency(nTotal) & "</B></TD></TR>" & vbCrLf
     Out "<TR><TD COLSPAN=5 ALIGN=""RIGHT"">"
     Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Shop for more"">&nbsp;"
     Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Recalculate"">&nbsp;"
     Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Check out"">"
     Out "</TD></TR></TABLE></FORM>"
End Sub


Don't know if this is a problem - but the form must 'resubmit' when the user clicks on  a button and then know which button was clicked - it currently does the following on submit:

' add or modify products
If Request.ServerVariables("CONTENT_LENGTH") > 0 Then
     Select Case Trim(Request.Form("DO"))
          Case "Shop for more"
               Response.Redirect "products.asp"
               Response.End
          Case "Recalculate"
               RecalcBag BagItems
          Case "Check out"
               ' recalculate and then redirect to checkout
     End Select
Else
     ' products are added using the query string
     nProductId = Trim(Request.QueryString("id"))
     AddtlProduct nProductId, BagItems
End If


Thank!
CEKMAN

0
Comment
Question by:cekman
  • 14
  • 7
21 Comments
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
we need to see exactly what is your code.
0
 
LVL 5

Author Comment

by:cekman
Comment Utility
My full code is at home - but it is pretty much exactly as the code shown above. I added one more button called "Submit Order" - and it is set up just like the other buttons shown in the original example. This button then calls a subroutine called sendemail (or something like that).

I'm pretty sure if you can show me how to change the example - then I can apply that to my code. But if you need the full code that I use I can copy it tonight.  However - I think it will add a lot of confusion.

Let me know if you want to wait. Thanks for your help.

Cekman
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
no need to wait. I know exactly what you have done =)
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
CODE
====
<%@language="VBScript"%>
<%
  Response.Buffer = True
  Function LoadXMLBag()
      Set XMLDoc = Server.CreateObject("Microsoft.XMLDOM")
      If Not IsEmpty(Session("BagItems")) Then
            XMLDoc.loadXML CStr(Session("BagItems"))
            Set BagItems = XMLDoc.documentElement
      Else
            Set BagItems = XMLDoc.createElement("BagItems")
            Set XMLDoc.documentElement = BagItems
      End If
      Set LoadXMLBag = BagItems
  End Function

Sub AddtlProduct(nProductId, BagItems)
      bValid = True
      
      If "" = nProductId Or Not IsNumeric(nProductId) Then
            bValid = False
      Else
            Set objConn = Server.CreateObject("ADODB.Connection")
            objConn.Open "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password=sangha05;"
            Set objRS = Server.CreateObject("ADODB.Recordset")
            Set objRS.ActiveConnection = objConn
            objRS.Open "SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice FROM Products WHERE ProductId=" & nProductId
            If objRS.EOF And objRS.BOF Then
                  bValid = False
            Else
                  avarProduct = objRS.GetRows()
            End If
            objConn.Close
            Set objRS = Nothing
            Set objConn = Nothing
      End If
      
      ' if the product was ok, add it to the bag
      If bValid Then
            AddProductToBag avarProduct, BagItems
      End If
End Sub

Sub AddProductToBag(avarProduct, BagItems)
      Set XMLDoc = BagItems.ownerDocument
      Set nodeFind = BagItems.selectNodes("product[@productid=""" & nProductId & """]")
      If Not nodeFind.length > 0 Then
            Set product = XMLDoc.createElement("product")
            Set attr = XMLDoc.createAttribute("productid")
            attr.Text = avarProduct(0,0)
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("productname")
            attr.Text = Server.HtmlEncode(avarProduct(1,0))
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("quantityperunit")
            attr.Text = Server.HtmlEncode(avarProduct(2,0))
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("unitprice")
            attr.Text = avarProduct(3,0)
            product.attributes.setNamedItem(attr)
            product.text = "1"
            BagItems.appendChild(product)
      End If
End Sub

Sub Out(strOut)
      Response.Write strOut
End Sub

Sub PrintBag(BagItems)
      Out "<FORM METHOD=""POST"" ACTION="""
      Out Request.ServerVariables("SCRIPT_NAME") & """ name=form1" & """ id=form1>"
      Out "<TABLE><TR><TH>Units</TH><TH COLSPAN=2>"
      Out "Product</TH><TH>Unit Price</TH><TH>Price</TH>"
      Out "</TR>" & vbCrLf
      For Each item In BagItems.childNodes
            Out "<TR><TD><input type=""TEXT"" name=""Qty"
            Out item.attributes.getNamedItem("productid").nodeValue
            Out """ VALUE=""" & item.text & """ SIZE=""3"">"
            Out "<TD>" & item.attributes.getNamedItem("productname").nodeValue
            Out "</TD><TD>" & item.attributes.getNamedItem("quantityperunit").nodeValue & "</TD>"
            nUnitPrice = item.attributes.getNamedItem("unitprice").nodeValue
            nSubTotal = item.text * nUnitPrice
            nTotal = nTotal + nSubTotal
            Out "<TD>" & FormatCurrency(nUnitPrice) & "</TD>"
            Out "<TD><B>" & FormatCurrency(nSubTotal) & "</B></TD>"
            Out "</TR>" & vbCRLF
      Next
      Out "<TR><TD COLSPAN=5><HR></TD></TR>"
      Out "<TR><TD COLSPAN=3></TD><TD><B>Total:</B></TD>"
      Out "<TD><B>" & FormatCurrency(nTotal) & "</B></TD></TR>" & vbCrLf
      Out "<TR><TD COLSPAN=5 ALIGN=""RIGHT"">"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Shop for more"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Recalculate"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Check out"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Submit Order"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
      Out "</TD></TR></TABLE></FORM>"
End Sub

Sub RecalcBag(BagItems)
      For Each item in BagItems.childNodes
            nQty = Trim(Request.Form("Qty" & item.attributes.getNamedItem("productid").nodeValue))
            If "" <> nQty And IsNumeric(nQty) Then
                  If nQty < 1 Then
                        BagItems.removeChild item
                  Else
                        item.text = nQty
                  End If
            End If
      Next
End Sub
%>
<html>
<head>
      <title>Implementing the Shopping Bag</title>
      <script language="javascript">
      var bolEnter = false;
      function checkKey(iKey) {
        bolEnter = iKey != 13;
      }
      function validateForm() {
        var bolReturn = ! bolEnter;
        bolEnter = false;
        return bolReturn;
      }
      </script>
</head>
<body bgcolor="#ffffff">
<%
On Error Resume Next
' get or create the bag
Set BagItems = LoadXMLBag()

' add or modify products
If Request.ServerVariables("CONTENT_LENGTH") > 0 Then
      Select Case Trim(Request.Form("DO"))
            Case "Shop for more"
                  Response.Redirect "products.asp"
                  Response.End
            Case "Recalculate"
                  RecalcBag BagItems
            Case "Check out"
                  Response.Write "<DIV>You have checked out</DIV>"
            Case "Submit Order"
              Response.Write "<DIV>You have submitted mail</DIV>"
      End Select
Else
      ' products are added using the query string
      nProductId = Trim(Request.QueryString("id"))
      AddtlProduct nProductId, BagItems
End If

Session("BagItems") = BagItems.XML

If BagItems.hasChildNodes Then
      PrintBag BagItems
Else
      Response.Write "Sorry, you have no items in your bag!"
End If
%>
</body>
</html>

0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
Notes
=====
The changes to the code are as follows:

1. script
<script language="javascript">
var bolEnter = false;
function checkKey(iKey) {
  bolEnter = iKey != 13;
}
function validateForm() {
  var bolReturn = ! bolEnter;
  bolEnter = false;
  return bolReturn;
}
</script>

2. submit buttons
Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Shop for more"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Recalculate"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Check out"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Submit Order"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
     
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
The rationale
=============
we use the keyup event to trap the key used on the button. if the key used is 13 (ENTER), we set the bolEnter equals to true.

Next, and this is the important part, we return the inverse value of bolEnter via a proxy variable, bolReturn. We then reset the bolEnter value to false. This is important becos users could use the tab key to toggle between inputs. Now, the long and short of it is that if the bolEnter is true meaning the key pressed was Enter, the return value is false. By passing that value thru return validateForm(); we stop the submission of the form
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
tested with MSIE4+, NS 6.2
0
 
LVL 5

Author Comment

by:cekman
Comment Utility
Thank you!  I'll try these changes when I get home tonight. If it doesn't work - I'll post my entire code.

I REALLY appreciate the help!

CEKMAN
0
 
LVL 5

Author Comment

by:cekman
Comment Utility
If a visitor does not have the necessary 'browser' or 'settings' (not exactly sure of what I"m talking about here')  will my site bomb for them or will the ENTER key just submit the form like it does now?

With the JAVA code - will non-java enabled visitors even be able to use the shopping bag feature?

If not - what percentage of users would this affect in your opinion??

CEKMAN
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
if a user disables javascript, well there's nothing to stop them from using the ENTER key. These days, most sites require javascript.

so the user disables javascript, 99% of e-commerce sites won't work for them. Discount users that disable javascript. They are so miniscule.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 5

Author Comment

by:cekman
Comment Utility
OK - I put your code in as best I could - but it's not working - same results. Every time I press ENTER the form submits and the fields are cleared.

To try it as it stands now with the changes go here:

http://www.cobweb-corner.com/crossstitchscart.htm

Only the keyword search works. Add an item to the shopping cart - then just press ENTER - and you'll see what's happening.

I KNOW the code is probably sloppy - but I'm and Access programmer - not a web programmer. I never saw this stuff before last Friday - so bear with me.

Here's my code in its entirety for bag.asp - Thanks for your help! Good luck!!!



<%@language="VBScript"%>
<% Response.Buffer = True %>
<html>
<head>
      <title>Implementing the Shopping Bag</title>
</head>
<body bgcolor="#ffffff">
<%
' get or create the bag
Set BagItems = LoadXMLBag()

' add or modify products
If Request.ServerVariables("CONTENT_LENGTH") > 0 Then
      Select Case Trim(Request.Form("DO"))
            Case "Shop for more Cross Stitch"
                  Response.Redirect "crossstitchscart.htm"
                  Response.End
            Case "Recalculate"
                  RecalcBag BagItems
            Case "Submit Order"
                  EmailForm
      End Select
Else
      ' products are added using the query string
      nProductId = Trim(Request.QueryString("id"))
      AddtlProduct nProductId, BagItems
End If

Session("BagItems") = BagItems.XML

If BagItems.hasChildNodes Then
      PrintBag BagItems
Else
      Response.Write "Sorry, you have no items in your bag!"
End If
%>
</body>
</html>
<script language="javascript">
var bolEnter = false;
function checkKey(iKey) {
bolEnter = iKey != 13;
}
function validateForm() {
var bolReturn = ! bolEnter;
bolEnter = false;
return bolReturn;
}
</script>

<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Function LoadXMLBag()
      Set XMLDoc = Server.CreateObject("Microsoft.XMLDOM")
      If Not IsEmpty(Session("BagItems")) Then
            XMLDoc.loadXML CStr(Session("BagItems"))
            Set BagItems = XMLDoc.documentElement
      Else
            Set BagItems = XMLDoc.createElement("BagItems")
            Set XMLDoc.documentElement = BagItems
      End If
      Set LoadXMLBag = BagItems
End Function

Sub AddtlProduct(nProductId, BagItems)
      bValid = True
      
      If "" = nProductId Or Not IsNumeric(nProductId) Then
            bValid = False
      Else


      'adovbs constants
      Const adUseClient = 3
      Const adOpenStatic = 3
      Const adLockReadOnly = 1

      Set objConn = Server.CreateObject("ADODB.Connection")
      Set objrs = Server.CreateObject("ADODB.Recordset")

      strDSN = "DSN=XSDSN"

      objConn.Open strDSN
      objrs.CursorLocation = adUseClient

      Set objRS.ActiveConnection = objConn

      strSQL = "SELECT productid,productname, itemnbr, unitprice FROM tblWebSearchsc WHERE  productid=" & nProductId

      objRS.Open strSQL,objConn,adOpenStatic,adLockReadOnly

            If objRS.EOF And objRS.BOF Then
                  bValid = False
            Else
                  avarProduct = objRS.GetRows()
                  
            End If
            objConn.Close
            Set objRS = Nothing
            Set objConn = Nothing
      End If
      
      ' if the product was ok, add it to the bag
      If bValid Then
            AddProductToBag avarProduct, BagItems
      End If
End Sub

Sub AddProductToBag(avarProduct, BagItems)
      Set XMLDoc = BagItems.ownerDocument
      Set nodeFind = BagItems.selectNodes("product[@productid=""" & nProductId & """]")
      If Not nodeFind.length > 0 Then

            Set product = XMLDoc.createElement("product")
            Set attr = XMLDoc.createAttribute("productid")
            attr.Text = avarProduct(0,0)
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("productname")
            attr.Text = Server.HtmlEncode(avarProduct(1,0))
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("itemnbr")
            attr.Text = Server.HtmlEncode(avarProduct(2,0))
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("unitprice")
            attr.Text = avarProduct(3,0)
            product.attributes.setNamedItem(attr)
            product.text = "1"
            BagItems.appendChild(product)
      End If
End Sub

Sub Out(strOut)
      Response.Write strOut
End Sub

Sub PrintBag(BagItems)
      Out "<FORM METHOD=""POST"" ACTION="""
      Out Request.ServerVariables("SCRIPT_NAME") & """>"
      Out "<TABLE><TR><TH>Qty</TH><TH>"
      Out "Item Name</TH><TH>Item Nbr</TH><TH>Price</TH><TH>Total</TH>"
      Out "</TR>" & vbCrLf
      For Each item In BagItems.childNodes
            Out "<TR><TD><input type=""TEXT"" name=""Qty"
            Out item.attributes.getNamedItem("productid").nodeValue
            Out """ VALUE=""" & item.text & """ SIZE=""3"">"
            Out "<TD>" & item.attributes.getNamedItem("productname").nodeValue
            Out "</TD><TD>" & item.attributes.getNamedItem("itemnbr").nodeValue & "</TD>"
            nUnitPrice = item.attributes.getNamedItem("unitprice").nodeValue
            nSubTotal = item.text * nUnitPrice
            nTotal = nTotal + nSubTotal
            Out "<TD>" & FormatCurrency(nUnitPrice) & "</TD>"
            Out "<TD><B>" & FormatCurrency(nSubTotal) & "</B></TD>"
            Out "</TR>" & vbCRLF
      Next
      Out "<TR><TD COLSPAN=5><HR></TD></TR>"
      Out "<TR><TD COLSPAN=3></TD><TD><B>Total:</B></TD>"
      Out "<TD><B>" & FormatCurrency(nTotal) & "</B></TD></TR>" & vbCrLf
      Out "<TR><TD COLSPAN=5 ALIGN=""RIGHT"">"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Shop for more Cross Stitch"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Recalculate"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"


      Out "</TD></TR></TABLE></p>"
      Out "To remove something from your cart enter 0 for Qty and press Recalculate. <br> We do not guarantee "
      Out "that we will have multiples of an item. You may request more than one and we will let you know what we have."
      Out "<hr>"
      Out "<font size=""3"" color=""#FF0000"">Ready to Check Out?</font>"
      Out "<br>"
      Out "When done click on the Submit Order button at the bottom of the page."
      Out "<br>"
      Out "We will contact you as soon as possible with final availability, shipping cost and payment details."
      Out "</p>"
      Out "<p>Your name: <input type=""TEXT"" size = ""30"" name=""visitor_name"">&nbsp;&nbsp;"
      Out "<input type=""checkbox"" name=""copyemail"" value=""ON"">&nbsp; check box if you want a copy of email sent to you."
      Out "<br>"
            Out "Your Email Address:&nbsp;<input type=""TEXT"" size=""40"" name=""visitor_email""><br> Required! We can't respond without a valid email address."
      Out "</p>"      
      Out "<TABLE><TR>"      
      Out "<TD align=""right"" valign=""top"">Address:</TD><TD> <input type=""TEXT"" size=""50"" name=""address1""><br>"
      Out "<input type=""TEXT"" size=""50"" name=""address2""></TD></TR>"
      Out "<TR><TD align=""right"">City:</TD>"
      Out "<TD><input type=""TEXT"" name=""city"">"
      Out "&nbsp;St/Prov:&nbsp;"
      Out "<input type=""TEXT"" name=""state"" size=""2"">&nbsp;"
      Out "Zip/Post:&nbsp;<input type=""TEXT"" size=""12"" name=""zipcode""></TD></TR>"
      Out "<TR><TD align=""right"">Country:&nbsp;</TD>"
      Out "<TD><input type=""TEXT"" name=""country"" size=""25""></TD></TR>"
      Out "</TABLE>"
      Out "</p>Enter additional comments/questions here. Don't send credit card information.<br>"
      Out "<textarea name=""body"" rows=""10"" cols=""60""></textarea>"
      Out "Click here to send us your order. <INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Submit Order"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"

      Out "</p></FORM>"

      Out "</form>"      
End Sub

Sub RecalcBag(BagItems)
      For Each item in BagItems.childNodes
            nQty = Trim(Request.Form("Qty" & item.attributes.getNamedItem("productid").nodeValue))
            If "" <> nQty And IsNumeric(nQty) Then
                  If nQty < 1 Then
                        BagItems.removeChild item
                  Else
                        item.text = nQty
                  End If
            End If
      Next
End Sub

Sub EmailForm
Dim emailAddress
Dim strMsgBody

emailAddress = Request("visitor_email")
response.write emailAddress
if emailAddress <> "" then
      response.write "Email Address <> blank"
      emailAddress = Cstr(emailAddress)
      if emailAddress <> "" then
            blnValidEmail = RegExpTest(emailAddress)
            if not blnValidEmail then
                  Response.Redirect "http://cobweb-corner.com/validateform.htm"
                  Response.End
            else
                  Set Mail = Server.CreateObject("Persits.MailSender")
                  Mail.Host = "cobweb-corner.com" ' Specify your domain
                  Mail.From = Trim(Request("visitor_email")) ' Specify sender's address
                  Mail.FromName = Trim(Request("visitor_name")) ' Specify sender's name

                  Mail.AddAddress "cekman@cobweb-corner.com"
                  if Request("copyemail") = "ON" then
                        Mail.AddAddress emailaddress
                  End If

                  Mail.AddReplyTo Trim(Request("visitor_email"))


                  Mail.Subject = "Order Inquiry from Cobweb Corner"
                  strMsgBody = "Visitor Name: " & Trim(Request("visitor_name")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Visitor Email: " & Trim(Request("visitor_email")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Address: " & Trim(Request("address1")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Address: " & Trim(Request("address2")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "  " & Trim(Request("city")) & "  " & Trim(Request("state"))
                  strMsgBody = strMsgBody & "  " & Trim(Request("zipcode")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Questions/Comments: " & Trim(Request("body")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & chr(13) & chr(10)
                  If BagItems.hasChildNodes() Then
                        For Each item In BagItems.childNodes
                              strMsgBody = strMsgBody & item.attributes.getNamedItem("itemnbr").nodeValue & "  "
                              strMsgBody = strMsgBody & item.attributes.getNamedItem("productname").nodeValue & "  "
                              strMsgBody = strMsgBody & item.text & " *  "
                              nUnitPrice = item.attributes.getNamedItem("unitprice").nodeValue
                              nSubTotal = nUnitPrice * item.text
                              nTotal = nTotal + nSubTotal
                              strMsgBody = strMsgBody & FormatCurrency(nUnitPrice)  & " = " & FormatCurrency(nSubTotal)
                              strMsgBody = strMsgBody & chr(13) & chr(10)
                        Next
                  End If
                  strMsgBody = strMsgBody & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Total without shipping: " & FormatCurrency(nTotal) & chr(13) & chr(10) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Thank you for visiting Cobweb Corner!" & chr(13) & chr(10) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "We will contact you as soon as possible with information regarding availability and shipping - or with answers to your questions."
                  
                  Mail.Body = strMsgBody

                  On Error Resume Next
                  Mail.Send
                  If Err <> 0 Then
                        Response.Write "Error encountered: " & Err.Description
                  else
                        Response.Redirect "thankyou.htm"
                  End If
                  Response.End
            End If
      else
            Response.Redirect "http://cobweb-corner.com/validateform.htm"
            Response.End
      End If
Else
            Response.Redirect "http://cobweb-corner.com/validateform.htm"
            Response.End
End if


End Sub
Function RegExpTest(sEmail)
Response.write "Got to function"
RegExpTest = false
Dim regEx, retVal
Set regEx = New RegExp

' Create regular expression:
regEx.Pattern ="^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"

' Set pattern:
regEx.IgnoreCase = true

' Set case sensitivity.
retVal = regEx.Test(sEmail)

' Execute the search test.
If not retVal Then
exit function
End If

RegExpTest = true
End Function
</SCRIPT>

0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
There is one simple change that needs to be done to complete the circle.

Sub PrintBag(BagItems)
Out "<FORM METHOD=""POST"" ACTION="""
Out Request.ServerVariables("SCRIPT_NAME") & """ ONKEYPRESS=""checkKey(event.keyCode);"">"
...

Notes
=====
1. The rest of the amended code is true when the button is in focus and the ENTER key is pressed.
2. What the amended code does is to reuse the checkKey so that when the form is in focus and not any particular button and the ENTER key is pressed, the same process kicks in and the form submission stops.
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
Explanation
===========
The reason for this anomaly arises from the fact that when the form is in focus, one of the buttons is in focus too thereby bypassing albeit as a secondary focused item. This means that because the button is not directly in focus, the keypress event of the button never fires which then leads to the form submission going thru. The solution is to place the checkKey() method on the keypress event of the form to account for this abherrant behaviour.
0
 
LVL 5

Author Comment

by:cekman
Comment Utility
Thanks for the help - but I must still be doing something wrong. It doesn't work. If I push ENTER it executes the "Shop for More Cross Stitch" button. Could it be the CASE statement? Do I need an ELSE that 'does nothing' if no buttons are clicked? It certainly isn't 'ignoring' the ENTER key. Here's my code one more time - I'm on my way to work and won't be able to try more until this evening...

<%@language="VBScript"%>
<% Response.Buffer = True %>
<html>
<head>
      <title>Implementing the Shopping Bag</title>
</head>
<body bgcolor="#ffffff">
<%
' get or create the bag
Set BagItems = LoadXMLBag()

' add or modify products
If Request.ServerVariables("CONTENT_LENGTH") > 0 Then
      Select Case Trim(Request.Form("DO"))
            Case "Shop for more Cross Stitch"
                  Response.Redirect "crossstitchscart.htm"
                  Response.End
            Case "Recalculate"
                  RecalcBag BagItems
            Case "Submit Order"
                  EmailForm
      End Select
Else
      ' products are added using the query string
      nProductId = Trim(Request.QueryString("id"))
      AddtlProduct nProductId, BagItems
End If

Session("BagItems") = BagItems.XML

If BagItems.hasChildNodes Then
      PrintBag BagItems
Else
      Response.Write "Sorry, you have no items in your bag!"
End If
%>
</body>
</html>
<script language="javascript">
var bolEnter = false;
function checkKey(iKey) {
bolEnter = iKey != 13;
}
function validateForm() {
var bolReturn = ! bolEnter;
bolEnter = false;
return bolReturn;
}
</script>

<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Function LoadXMLBag()
      Set XMLDoc = Server.CreateObject("Microsoft.XMLDOM")
      If Not IsEmpty(Session("BagItems")) Then
            XMLDoc.loadXML CStr(Session("BagItems"))
            Set BagItems = XMLDoc.documentElement
      Else
            Set BagItems = XMLDoc.createElement("BagItems")
            Set XMLDoc.documentElement = BagItems
      End If
      Set LoadXMLBag = BagItems
End Function

Sub AddtlProduct(nProductId, BagItems)
      bValid = True
      
      If "" = nProductId Or Not IsNumeric(nProductId) Then
            bValid = False
      Else


      'adovbs constants
      Const adUseClient = 3
      Const adOpenStatic = 3
      Const adLockReadOnly = 1

      Set objConn = Server.CreateObject("ADODB.Connection")
      Set objrs = Server.CreateObject("ADODB.Recordset")

      strDSN = "DSN=XSDSN"

      objConn.Open strDSN
      objrs.CursorLocation = adUseClient

      Set objRS.ActiveConnection = objConn

      strSQL = "SELECT productid,productname, itemnbr, unitprice FROM tblWebSearchsc WHERE  productid=" & nProductId

      objRS.Open strSQL,objConn,adOpenStatic,adLockReadOnly

            If objRS.EOF And objRS.BOF Then
                  bValid = False
            Else
                  avarProduct = objRS.GetRows()
                  
            End If
            objConn.Close
            Set objRS = Nothing
            Set objConn = Nothing
      End If
      
      ' if the product was ok, add it to the bag
      If bValid Then
            AddProductToBag avarProduct, BagItems
      End If
End Sub

Sub AddProductToBag(avarProduct, BagItems)
      Set XMLDoc = BagItems.ownerDocument
      Set nodeFind = BagItems.selectNodes("product[@productid=""" & nProductId & """]")
      If Not nodeFind.length > 0 Then

            Set product = XMLDoc.createElement("product")
            Set attr = XMLDoc.createAttribute("productid")
            attr.Text = avarProduct(0,0)
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("productname")
            attr.Text = Server.HtmlEncode(avarProduct(1,0))
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("itemnbr")
            attr.Text = Server.HtmlEncode(avarProduct(2,0))
            product.attributes.setNamedItem(attr)
            Set attr = XMLDoc.createAttribute("unitprice")
            attr.Text = avarProduct(3,0)
            product.attributes.setNamedItem(attr)
            product.text = "1"
            BagItems.appendChild(product)
      End If
End Sub

Sub Out(strOut)
      Response.Write strOut
End Sub

Sub PrintBag(BagItems)
      Out "Test 1"
      Out "<FORM METHOD=""POST"" ACTION="""
      Out Request.ServerVariables("SCRIPT_NAME") & """ ONKEYPRESS=""checkKey(event.keyCode);"">"
      Out "<TABLE><TR><TH>Qty</TH><TH>"
      Out "Item Name</TH><TH>Item Nbr</TH><TH>Price</TH><TH>Total</TH>"
      Out "</TR>" & vbCrLf
      For Each item In BagItems.childNodes
            Out "<TR><TD><input type=""TEXT"" name=""Qty"
            Out item.attributes.getNamedItem("productid").nodeValue
            Out """ VALUE=""" & item.text & """ SIZE=""3"">"
            Out "<TD>" & item.attributes.getNamedItem("productname").nodeValue
            Out "</TD><TD>" & item.attributes.getNamedItem("itemnbr").nodeValue & "</TD>"
            nUnitPrice = item.attributes.getNamedItem("unitprice").nodeValue
            nSubTotal = item.text * nUnitPrice
            nTotal = nTotal + nSubTotal
            Out "<TD>" & FormatCurrency(nUnitPrice) & "</TD>"
            Out "<TD><B>" & FormatCurrency(nSubTotal) & "</B></TD>"
            Out "</TR>" & vbCRLF
      Next
      Out "<TR><TD COLSPAN=5><HR></TD></TR>"
      Out "<TR><TD COLSPAN=3></TD><TD><B>Total:</B></TD>"
      Out "<TD><B>" & FormatCurrency(nTotal) & "</B></TD></TR>" & vbCrLf
      Out "<TR><TD COLSPAN=5 ALIGN=""RIGHT"">"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Shop for more Cross Stitch"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"
      Out "<INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Recalculate"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"


      Out "</TD></TR></TABLE></p>"
      Out "To remove something from your cart enter 0 for Qty and press Recalculate. <br> We do not guarantee "
      Out "that we will have multiples of an item. You may request more than one and we will let you know what we have."
      Out "<hr>"
      Out "<font size=""3"" color=""#FF0000"">Ready to Check Out?</font>"
      Out "<br>"
      Out "When done click on the Submit Order button at the bottom of the page."
      Out "<br>"
      Out "We will contact you as soon as possible with final availability, shipping cost and payment details."
      Out "</p>"
      Out "<p>Your name: <input type=""TEXT"" size = ""30"" name=""visitor_name"">&nbsp;&nbsp;"
      Out "<input type=""checkbox"" name=""copyemail"" value=""ON"">&nbsp; check box if you want a copy of email sent to you."
      Out "<br>"
            Out "Your Email Address:&nbsp;<input type=""TEXT"" size=""40"" name=""visitor_email""><br> Required! We can't respond without a valid email address."
      Out "</p>"      
      Out "<TABLE><TR>"      
      Out "<TD align=""right"" valign=""top"">Address:</TD><TD> <input type=""TEXT"" size=""50"" name=""address1""><br>"
      Out "<input type=""TEXT"" size=""50"" name=""address2""></TD></TR>"
      Out "<TR><TD align=""right"">City:</TD>"
      Out "<TD><input type=""TEXT"" name=""city"">"
      Out "&nbsp;St/Prov:&nbsp;"
      Out "<input type=""TEXT"" name=""state"" size=""2"">&nbsp;"
      Out "Zip/Post:&nbsp;<input type=""TEXT"" size=""12"" name=""zipcode""></TD></TR>"
      Out "<TR><TD align=""right"">Country:&nbsp;</TD>"
      Out "<TD><input type=""TEXT"" name=""country"" size=""25""></TD></TR>"
      Out "</TABLE>"
      Out "</p>Enter additional comments/questions here. Don't send credit card information.<br>"
      Out "<textarea name=""body"" rows=""10"" cols=""60""></textarea>"
      Out "Click here to send us your order. <INPUT TYPE=SUBMIT NAME=""DO"" VALUE=""Submit Order"" ONKEYUP=""checkKey(event.keyCode);"" ONCLICK=""return validateForm();"">&nbsp;"

      Out "</p></FORM>"

      Out "</form>"      
End Sub

Sub RecalcBag(BagItems)
      For Each item in BagItems.childNodes
            nQty = Trim(Request.Form("Qty" & item.attributes.getNamedItem("productid").nodeValue))
            If "" <> nQty And IsNumeric(nQty) Then
                  If nQty < 1 Then
                        BagItems.removeChild item
                  Else
                        item.text = nQty
                  End If
            End If
      Next
End Sub

Sub EmailForm
Dim emailAddress
Dim strMsgBody

emailAddress = Request("visitor_email")
response.write emailAddress
if emailAddress <> "" then
      response.write "Email Address <> blank"
      emailAddress = Cstr(emailAddress)
      if emailAddress <> "" then
            blnValidEmail = RegExpTest(emailAddress)
            if not blnValidEmail then
                  Response.Redirect "http://cobweb-corner.com/validateform.htm"
                  Response.End
            else
                  Set Mail = Server.CreateObject("Persits.MailSender")
                  Mail.Host = "cobweb-corner.com" ' Specify your domain
                  Mail.From = Trim(Request("visitor_email")) ' Specify sender's address
                  Mail.FromName = Trim(Request("visitor_name")) ' Specify sender's name

                  Mail.AddAddress "cekman@cobweb-corner.com"
                  if Request("copyemail") = "ON" then
                        Mail.AddAddress emailaddress
                  End If

                  Mail.AddReplyTo Trim(Request("visitor_email"))


                  Mail.Subject = "Order Inquiry from Cobweb Corner"
                  strMsgBody = "Visitor Name: " & Trim(Request("visitor_name")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Visitor Email: " & Trim(Request("visitor_email")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Address: " & Trim(Request("address1")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Address: " & Trim(Request("address2")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "  " & Trim(Request("city")) & "  " & Trim(Request("state"))
                  strMsgBody = strMsgBody & "  " & Trim(Request("zipcode")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Questions/Comments: " & Trim(Request("body")) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & chr(13) & chr(10)
                  If BagItems.hasChildNodes() Then
                        For Each item In BagItems.childNodes
                              strMsgBody = strMsgBody & item.attributes.getNamedItem("itemnbr").nodeValue & "  "
                              strMsgBody = strMsgBody & item.attributes.getNamedItem("productname").nodeValue & "  "
                              strMsgBody = strMsgBody & item.text & " *  "
                              nUnitPrice = item.attributes.getNamedItem("unitprice").nodeValue
                              nSubTotal = nUnitPrice * item.text
                              nTotal = nTotal + nSubTotal
                              strMsgBody = strMsgBody & FormatCurrency(nUnitPrice)  & " = " & FormatCurrency(nSubTotal)
                              strMsgBody = strMsgBody & chr(13) & chr(10)
                        Next
                  End If
                  strMsgBody = strMsgBody & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Total without shipping: " & FormatCurrency(nTotal) & chr(13) & chr(10) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "Thank you for visiting Cobweb Corner!" & chr(13) & chr(10) & chr(13) & chr(10)
                  strMsgBody = strMsgBody & "We will contact you as soon as possible with information regarding availability and shipping - or with answers to your questions."
                  
                  Mail.Body = strMsgBody

                  On Error Resume Next
                  Mail.Send
                  If Err <> 0 Then
                        Response.Write "Error encountered: " & Err.Description
                  else
                        Response.Redirect "thankyou.htm"
                  End If
                  Response.End
            End If
      else
            Response.Redirect "http://cobweb-corner.com/validateform.htm"
            Response.End
      End If
Else
            Response.Redirect "http://cobweb-corner.com/validateform.htm"
            Response.End
End if


End Sub
Function RegExpTest(sEmail)
Response.write "Got to function"
RegExpTest = false
Dim regEx, retVal
Set regEx = New RegExp

' Create regular expression:
regEx.Pattern ="^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"

' Set pattern:
regEx.IgnoreCase = true

' Set case sensitivity.
retVal = regEx.Test(sEmail)

' Execute the search test.
If not retVal Then
exit function
End If

RegExpTest = true
End Function
</SCRIPT>

0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
sorry about that, I can assure that it finally works LOL!

the script is:

<script language="javascript">
var bolEnter = false;
function checkKey(iKey) {
bolEnter = iKey == 13;
alert(iKey + "\n" + bolEnter);
}
function validateForm() {
var bolReturn = ! bolEnter;
alert(bolReturn);
bolEnter = false;
return bolReturn;
}
</script>
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
repost with the debugging code
================================
<script language="javascript">
var bolEnter = false;
function checkKey(iKey) {
bolEnter = iKey == 13;
}
function validateForm() {
var bolReturn = ! bolEnter;
bolEnter = false;
return bolReturn;
}
</script>

also, please place the script tag inside the head element

<html>
<head>
...
<script language="javascript">

</script>
</head>
<body>
..
</body>
</html>
0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
an example of this would be this static web page
================================================

<html>
<head>
     <title>Implementing the Shopping Bag</title>
<script language="javascript">
var bolEnter = false;
function checkKey(iKey) {
bolEnter = iKey == 13;
}
function validateForm() {
var bolReturn = ! bolEnter;
bolEnter = false;
return bolReturn;
}
</script>
</head>
<body bgcolor="#ffffff">
Test 1<FORM METHOD="POST" ACTION="/bag.asp" ONKEYPRESS="checkKey(event.keyCode);"><TABLE><TR><TH>Qty</TH><TH>Item Name</TH><TH>Item Nbr</TH><TH>Price</TH><TH>Total</TH></TR>
<TR><TD><input type="TEXT" name="Qty776" VALUE="1" SIZE="3"><TD>&quot;T&quot; Is For Teacher</TD><TD>CS611CE</TD><TD>$5.00</TD><TD><B>$5.00</B></TD></TR>
<TR><TD COLSPAN=5><HR></TD></TR><TR><TD COLSPAN=3></TD><TD><B>Total:</B></TD><TD><B>$5.00</B></TD></TR>
<TR><TD COLSPAN=5 ALIGN="RIGHT"><INPUT TYPE=SUBMIT NAME="DO" VALUE="Shop for more Cross Stitch" ONKEYUP="checkKey(event.keyCode);" ONCLICK="return validateForm();">&nbsp;<INPUT TYPE=SUBMIT NAME="DO" VALUE="Recalculate" ONKEYUP="checkKey(event.keyCode);" ONCLICK="return validateForm();">&nbsp;</TD></TR></TABLE></p>To remove something from your cart enter 0 for Qty and press Recalculate. <br> We do not guarantee that we will have multiples of an item. You may request more than one and we will let you know what we have.<hr><font size="3" color="#FF0000">Ready to Check Out?</font><br>When done click on the Submit Order button at the bottom of the page.<br>We will contact you as soon as possible with final availability, shipping cost and payment details.</p><p>Your name: <input type="TEXT" size = "30" name="visitor_name">&nbsp;&nbsp;<input type="checkbox" name="copyemail" value="ON">&nbsp; check box if you want a copy of email sent to you.<br>Your Email Address:&nbsp;<input type="TEXT" size="40" name="visitor_email"><br> Required! We can't respond without a valid email address.</p><TABLE><TR><TD align="right" valign="top">Address:</TD><TD> <input type="TEXT" size="50" name="address1"><br><input type="TEXT" size="50" name="address2"></TD></TR><TR><TD align="right">City:</TD><TD><input type="TEXT" name="city">&nbsp;St/Prov:&nbsp;<input type="TEXT" name="state" size="2">&nbsp;Zip/Post:&nbsp;<input type="TEXT" size="12" name="zipcode"></TD></TR><TR><TD align="right">Country:&nbsp;</TD><TD><input type="TEXT" name="country" size="25"></TD></TR></TABLE></p>Enter additional comments/questions here. Don't send credit card information.<br><textarea name="body" rows="10" cols="60"></textarea>Click here to send us your order. <INPUT TYPE=SUBMIT NAME="DO" VALUE="Submit Order" ONKEYUP="checkKey(event.keyCode);" ONCLICK="return validateForm();">&nbsp;</p></FORM></form>
</body>
</html>


0
 
LVL 23

Expert Comment

by:b1xml2
Comment Utility
it was just one line lol,

bolEnter = iKey == 13;

it will always be true if the ENTER key is pressed. LOL! Dunno how the != came about LOL.
0
 
LVL 5

Author Comment

by:cekman
Comment Utility
Thanks for your prompt reply! When I get home from work I'll replace my java script with the new function and move it to be in the <head> tags. Will let you know how this goes!

CEKMAN
0
 
LVL 23

Accepted Solution

by:
b1xml2 earned 300 total points
Comment Utility
I see you have implemented the code, cekman =)))
0
 
LVL 5

Author Comment

by:cekman
Comment Utility
Yes - it works - I wanted to test it this evening to make sure. Thanks for your help!

I've submitted ANOTHER question - hope you'll take a look since you know what I'm trying to do.

CEKMAN
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now