Question

Get 0 to replace the NULL in the database if a checkbox is unchecked by the user....

Asked by: Gemini532

Hello Everyone, I need some code which will replace NULL with 0 in the database when a checkbox in unchecked by the user, when the page is submitted... even if the checkbox is not touched by the user, that means it remains unchecked, since they're all unchecked to begin with, even then it should change to 0 when the user moves on to the next page....

This application has 3 pages and you can navigate either with Previous or Next buttons or by clicking the page number... All the pages are posted to the same validation page called save.asp and this page updates the database every time a user leaves the page...

The code on my first page has checkboxes which display as NULL in the database if they are not checked by the user and 1 if they are checked

Here is the code on the first page:

<form action="save.asp" id="OPICForm" name="OPICForm" method="post" onSubmit="return ValidateSubmit();">

<input type="checkbox" id="LearnConference" name="LearnConference" value = <%=sLearnConference%> <%=sLearnConferenceChecked %>>Conference<BR>

<input type="checkbox" id="LearnWebsite" name="LearnWebsite" value = <%=sLearnWebsite%> <%=sLearnWebsiteChecked%>>OPIC Web Site<BR>

<INPUT type="submit" style="width:75px;" value="Previous" onclick="setInputValue(document.OPICForm._target,'Previous');">
Jump to page: [<A href="javascript:SubmitForm('00');">Intro</A>]
<STRONG>[1]</STRONG> [<A
href="javascript:SubmitForm('02');">2</A>] [<A
href="javascript:SubmitForm('03');">3</A>] [<A
href="javascript:SubmitForm('04');">Review</A>] <INPUT type="submit" style="width:75px;" value="Next" onclick="setInputValue(document.OPICForm._target,'Next');">
<BR>
<input type = "submit" value = "Save and Close" id = "SaveClose" onclick="setInputValue(document.OPICForm._target,'SaveClose');">


<%
sqlValues = "SELECT * FROM tableName WHERE FK_id=" & id
set rsValues = Server.CreateObject("ADODB.Recordset")
with rsValues
.open sqlValues, objConn,3,3
if .Recordcount=1 then

      sLearnConference     = .Fields("LearnConference")
      sLearnWebsite              = .Fields("LearnWebsite")
end if
.close
end with

if .Fields("LearnConference")=true then sLearnConferenceChecked = " CHECKED " else sLearnConferenceChecked = "" end if
if .Fields("LearnWebsite")=true then sLearnWebsiteChecked = " CHECKED " else sLearnWebsiteChecked = "" end if

%>
<script>
function setInputValue(obj,value){
      var use_default=(arguments.length>1)?arguments[1]:false;
            if(isArray(obj)&&(typeof(obj.type)=="undefined")){
                  for(var i=0;i<obj.length;i++){
                        setSingleInputValue(obj[i],value);
                  }
            }
            else
            {
                  setSingleInputValue(obj,value);
            }
}
function setSingleInputValue(obj,value){switch(obj.type){case 'radio': case 'checkbox': if(obj.value==value){obj.checked=true;return true;}else{obj.checked=false;return false;}case 'text': case 'hidden': case 'textarea': case 'password': obj.value=value;return true;case 'select-one': case 'select-multiple':
var o=obj.options;for(var i=0;i<o.length;i++){if(o[i].value==value){o[i].selected=true;}else{o[i].selected=false;}}return true;}alert("FATAL ERROR: Field type "+obj.type+" is not supported for this function");return false;}
</script>


CODE ON the save.asp page (the page it's posting to:)

%
'Angie H. -- Test checkboxes
dim LearnConf, Website

'FIRST CHECKBOX -- CONFERENCE
If Request.Form("LearnConference") <> 1 then
 LearnConf = ""
Else
 LearnConf = "CHECKED"
End if

if((LearnConf) = "CHECKED") then
      Request.Form("LearnConference") = 0
end if

'SECOND CHECKBOX -- WEBSITE
If Request.Form("LearnWebsite") <> 1 then
 Website = ""
Else
 Website = "CHECKED"
End if

if((Website ) = "CHECKED") then
      Request.Form("LearnWebsite") = 0
end if
%>

Can you help me figure out what's wrong with this code, why it does not change the database value from NULL to 0 when the checkbox is unchecked?

I get this error when I click NEXT:
Microsoft VBScript runtime error '800a01b6'

Object doesn't support this property or method: 'Request.Form'

/angieapps/52/save_sv.asp, line 18

and it's coming from this line:
      Request.Form("LearnConference") = 0

I used this       Request.Form("LearnConference")  before without an error, but now it gives me an error because I try to change its value?!?!
Any ideas?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-05-17 at 08:21:46ID22578373
Tags

null

,

javascript

,

replace

,

0

Topics

JavaScript

,

Miscellaneous Web Development

,

Active Server Pages (ASP)

Participating Experts
3
Points
500
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. checkbox onclick
    Can You do This?? I have a checkbox but when clicked I want it to call an vb server side function only when its clicked. It seems to be calling the function(funtix) every time I write the checkbox not when the user clicks it? here is my code: <tr bgcolor="#EFEF...
  2. Getting info from unchecked checkboxes
    Alright. This should be a fairly simple question to answer, but I haven't been able to find any on the net. My problem is this. I have a form with some checkboxes in it. Once the user clicks submit, all the checkboxes that are checked, should send "checked" to th...
  3. checking/unchecking either checkbox should check/unch…
    I have a solution from a previous question that verifies that minimum quantities of checkboxes were checked. In that case, at least two of the first four checkboxes, one of the fifth, one of the sixth, and one of the last two were required. In the above case, all checkboxes h...
  4. specifying value for checkbox when unchecked
    I have a checkbox as follows <INPUT TYPE="checkbox" NAME="replacement" value="yes" <%if(replacement.equalsIgnoreCase("yes")) { %>checked<% } %> onclick="SetState(this, this.form.details)" > The "replac...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: nschaferPosted on 2007-05-17 at 08:49:37ID: 19109169

To start with, lets do a basic introduction into how check boxes work.  
Lets say I have a form with the following checkboxes:
  <input type="checkbox" name="check1" value="1" />
  <input type="checkbox" name="check1" value="2" />
  <input type="checkbox" name="check1" value="3" />
  <input type="checkbox" name="check2" value="1" />
  <input type="checkbox" name="check2" value="2" />
  <input type="checkbox" name="check2" value="3" />
So I have a total of 6 check boxes on the page, but notice only two different names.  This is common when the form is being generated by a database driven page.  
If I check the 1st and 3rd checkboxes of each group, then I send the following information to the action page of the form.
   check1 = "1,3"
   check2 = "1,3"
The values of the selected checkbox in a comma-delimited string are sent to the action page of the form.  Unchecked boxes are not sent at all.  So lets say I didn't check any of the boxes named check2 the info sent to the action page would be:
  check1 = "1,3"   Note check2 is not even included.

So looking at your code, it appears that you have only two checkboxes on the form and that they have different names.  If one or both of the checkboxes is not checked then they will not send any value to the save page.

Looking at your save.asp, one problem I see is code like the following:  Request.form("LearnConference") = 0  
This is simply invalid code.  You cannot set the value of an element of the Request object.  The request object is read only.  I'm not sure what you are trying to accomplish with this in any case.

What you need to do to update your database in your save page is to program your sql statement such that it inserts a 0 if the form item is empty.
   if request.form("LearnConference") = "1" then
     sql = sql & "LearnConference = 1,"
   else
     sql = sql & "LearnConference = 0,"
   end if
Using code like that to create your sql staement will allow you to put 1 in if the box is checked, and a 0 if it is not checked.  Depending on your database you could also write a trigger such that when a record is updated if the field value is null to set it to 0.   Another option is to use a stored procedure to update the table, and in the stored procedure have the logic to check for null value and convert it to a 0.  

So there are a few ways you can handle this, depending on your coding style and the database you are using.  I know you didn't post all of your code, and I'm not asking you to, but based on what I can see here there are a couple of concepts that you need to grasp better to resolve your issue.  

I hope this helps,

Neal.

 

by: Gemini532Posted on 2007-05-17 at 10:12:29ID: 19109849

All this would work if my database was updated by separate statments which update each form separately.  However, there is ONLY for universal code that updates every page on the database depending on its name which has to match the name on the form, and depending on its datatype...

Since you really understand what's going on I will include this code for you, maybe you can help... i know that changing the name for each checkbox to the same name would make my life a million times easier, but then the database will not know what's going on because each one of these separate names stands for a separate question, and this universal update will update ONLY one name if I remove the other 5 there's really 6 checkboxes,  but I only put 2 to make things easier...
In order to do this, they had to have name of the form the same as the name of the database table.  The name of the form elements is also the name of the database columns.  Also there's 13 different pages, not 3, but again, I wanted to cut down on the code...

Here's the code... Any ideas how to deal with something like this, probably your stored procedure or trigger ideas, only I've never programmed one of these before...

The code is this page (save.asp) is quite brilliant only it throws conventional programming right out of the wnidow...


dim iUserID, iApplicationID, iFormPart, sTable, sUpdate, bError
iUserID                  = Session("UserID")
iApplicationID      = Session("ApplicationID")
iFormPart            = Request.Form("_formpart")
response.write(iFormPart)
if iFormPart <> 0 and iFormPart <> 13 then
      
      
      sTable  = "form25part" & iFormPart
      
      ' Get the table properties
      dim rsTable
      set rsTable = Server.CreateObject("ADODB.Recordset")
      with objCommand
            .CommandText = "TableProperties"
            .Parameters.Append .CreateParameter("@TableName", adChar, adParamInput,12, sTable)
            set rsTable = .Execute
      end with      
      
      
      
      dim item, sqlUpdate, sValue, DataType
      
      for each item in Request.Form
            if left(item,1) <> "_" then
                  
                  sValue      = Request.Form(item)
                  if sValue = "" then
                        sValue="NULL"
                  else
                        ' Get the datatype
                        with rsTable
                              .Find "column_name='" & item & "'", 0, adSearchForward, adBookmarkFirst
                              if .BOF or .EOF then
                                    Response.Write("ERROR: Could not find datatype for column " & item & "<BR>")
                                    DataType = ""
                              else
                                    DataType = .Fields("datatype")
                              end if
                              
                        end with
                        
                        ' Format the variable based on the datatype
                        if sValue = "" then
                              sValue = "NULL"
                        else
                              select case DataType
                                    case "bit"
                                          if sValue="on" then
                                                sValue = 1
                                          elseif not IsNumeric(sValue) then
                                                sValue = "NULL"
                                          end if
                                    case "char", "varchar", "text"
                                          if trim(sValue) <> "" then
                                                sValue = "'" & SQLFriendly(sValue) & "'"
                                          else
                                                sValue = "NULL"
                                          end if
                                    case "datetime"
                                          if IsDate(sValue) then
                                                sValue = "'" & cDate(sValue) & "'"
                                          else
                                                sValue = "NULL"
                                          end if
                                    case "int"
                                          if not isNumeric(sValue) then
                                                sValue = "NULL"
                                          end if
                                    case "money"
                                          Response.Write(item & " - " & sValue & "<BR>")
                                          
                                          sValue = FormatCurrency(sValue,2,0,0,0)
                                    case else
                                          Response.Write("ERROR: Unknown Datatype '" & DataType & "' for column '" & item & "'")
                                          bError = true
                              end select
                        end if
                        
                        'if not isNumeric(sValue) then
                        '      sValue = "'" & SQLFriendly(sValue) & "'"
                        'end if
                  end if
                  
                  if DataType<>"" then
                        sUpdate = sUpdate & " [" & item & "]=" & sValue & ","
                  end if
            end if
      next
      
      if sUpdate<> "" then
            sUpdate = "UPDATE " & sTable & " SET " & sUpdate & " [Part" & iFormPart & "Complete]=" & Request.Form("_complete") & ", [Part" & iFormPart & "Updated_ts]='" & now() & "'" &_
                  " WHERE FK_ApplicationID=" & iApplicationID
      else
            sUpdate = "UPDATE " & sTable & " SET [Part" & iFormPart & "Complete]=" & Request.Form("_complete") & ", [Part" & iFormPart & "Updated_ts]='" & now() & "'" &_
                  " WHERE FK_ApplicationID=" & iApplicationID
      end if
      response.Write(sUpdate)
      objConn.execute(sUpdate)

end if

if not bError then
      dim s_target
      s_target = Request.Form("_target")

      select case s_target
            case "Next":            iFormPart = right("0" & cint(iFormPart)+1,2)
            case "Previous":      iFormPart = right("0" & cstr(cint(iFormPart)-1),2)
            case else:                  iFormPart = s_target
      end select
      
      Response.Redirect("25-" & iFormPart & ".asp")
end if

 

by: vnvkPosted on 2007-05-17 at 10:32:39ID: 19109987

Hi

Checked and Unchecked would be equal to true and false in bit notations.
In the first page where you are checking and assigning the values to sLearnConferenceChecked and sLEarnWebsiteChecked, you can make it look the way below:

if .Fields("LearnConference")=true then sLearnConferenceChecked = " 1" else sLearnConferenceChecked = "0" end if
if .Fields("LearnWebsite")=true then sLearnWebsiteChecked = " 1" else sLearnWebsiteChecked = "0" end if

I havent tested the code you had written, but that is the we resolved one of a similar issue.
Hope it helps

Kiran

 

by: alorentzPosted on 2007-05-17 at 12:15:36ID: 19110804

Use that nz() function I gave you the other day.  That way, the only values you will get are 1 and 0.  You put nz() around the value that you are using.

 

by: nschaferPosted on 2007-05-18 at 05:57:35ID: 19115109

The issue with the way your code works is that it assumes that the form object will include the field for the checkbox even if it is not checked.  As I mentioned above, this is not the case.  

If you re-write your save page to check for all of your possible checkbox names, the the code the vnvk has posted will work, because you will be looking for specific form fields and if they are not there then they won't have a value and so the variable will be set to 0.  You can do this though, Simply look through all of your pages and set write down all of the checkbox names.  Then add them all to your saveas page in a method similar to what vnvk has shown.

Another option would be to run add a small bit of javascript to each page.  You could do this with a seperate .js file so you don't have to include the actual function on each page.  Not really a lot difference in the work involved, but it would be cleaner that way.  The JS would run when you submit your form.  It could be made part of your ValidateSubmit function.  This javascript simply runs through all of the input elements on your page.  If they are checkboxes it checks to see if they are checked.  If they are not checked then it creates a hidden input element in the form with the same name as the checkbox and a value of 0.  This way your existing saveas.asp code will work because the form elements will exist ehter the checkbox is checked or not.

Hope this helps,

Neal.

=================================
function setCheck() {
  var input = document.getElementsByTagName("input")
  for (i=0;i<input.length;i++) {
    if (input[i].type == "checkbox" && input[i].checked == false) {
      var hid = document.createElement("input");
      hid.type = "hidden";
      hid.value = 0;
      hid.name = input[i].name;
      document.forms[0].appendChild(hid);
    }
  }  
}
=================================

 

by: Gemini532Posted on 2007-05-18 at 09:58:37ID: 19116958

Oh my God  nschafer!!!  You actually fixed it!  you know i've been working on this for over 3 weeks?
THANK YOU!!!  

 

by: nschaferPosted on 2007-05-18 at 10:31:47ID: 19117143

Glad I could help.

Neal.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...