Solved

using javascript to fill textbox values upon checkbox checked errors

Posted on 2003-11-12
18
3,488 Views
Last Modified: 2012-06-27
hey, i am trying to do the following and it is just not working. let me explain scenerio and then i will paste javascript and html below...

i have two checkboxes, electronic journal price and print journal price options. i have one textbox, Textbox1. the first checkbox, the electronic journal option ONLY shows up if the value for elective = "true", this is just a string, not a boolean, i have a string set to "true" that i pass through the javascript.  so, most of the time there will be just one checkbox (print journal) and one textbox (textbox1), but some of the time when conditions are met to make elective="true" then there are two checkboxes and 1 textbox.

when there are 2 checkboxes (when elective="true") i need the the checkboxes to act as they are adding upon each other, in other words, if you click the first one (electronic journal), you get a price of $20, but if you click the second one, even though the price for second one is $50, the price would be $70 instead. so i would take the ejournal cost and the pjournal cost together. if there are two checkboxes, one could never just get the cost for only the print journal, when they select the second checkbox (print journal), it includes the cost of the first checkbox (electronic journal)

i have attempted to work all this logic out in my code and i can't figure out what i am doing wrong.

------------------------------------------------------------------------

function ejournals_onclick(pjournalprice,ejournalprice,elective)
            {
            var pcks=document.Form1.elements['Checkbox1']
            var ecks=document.Form1.elements['Checkbox2']
            
            var txt=document.Form1.elements['TextBox1']
            var pcost=pjournalprice
            var ecost=ejournalprice
            
            if (ecks.checked != true)
            {
            txt.value =  0;
            pcks.checked = false;
            }
            else
            {
            txt.value = eval(ecost);
            pcks.checked = false;
            }
            }
            
            function pjournals_onclick(pjournalprice,ejournalprice,elective)
            {
            var pcks=document.Form1.elements['Checkbox1']
            var ecks=document.Form1.elements['Checkbox2']
            
            var txt=document.Form1.elements['TextBox1']
            var pcost=pjournalprice
            var ecost=ejournalprice
            
            if (elective != 'true')
            {
                  if (pcks.checked != true)
                  {
                  txt.value =  0;
                  }
                  else
                  {
                  txt.value = eval(pcost);
                  }
            else
            {
                  if (pcks.checked == true)
                  {
                  txt.value = eval(pcost) + eval(ecost);
                  ecks.checked = true;
                  }
                  if (pcks.checked == false && ecks.checked == true)
                  {
                  txt.value = eval(ecost);
                  }
                  if (pcks.checked == false && ecks.checked == false)
                  {
                  txt.value = 0
                  }
            }
            }


-----------------------------------------------------------------------------------------

                                                      <table cellSpacing="0" cellPadding="0" width="100%" border="0">
                                                            <tr>
                                                                  <td>
                                                                        <span><b><input id="Checkbox2" type="checkbox" name="Checkbox2" onclick="javascript:ejournals_onclick('20','50','true');" /><label for="Checkbox2">Electronic Subscription to <i>ToxSci</i></label></b></span>&nbsp;-
                                                                        <b>$
                                                                              <span id="ejournallabel">50</span></b></td>

                                                                  <td vAlign="bottom" align="right">&nbsp;</td>
                                                            </tr>
                                                      </table>
                                                
      </td></tr></table>
                                                <table cellSpacing="0" cellPadding="0" width="100%" border="0">
                                                      <tr>
                                                            <td>
                                                                  <span><b><input id="CheckBox1" type="checkbox" name="CheckBox1" onclick="javascript:pjournals_onclick('20','50','true');" /><label for="CheckBox1">Add Print Subscription to <i>ToxSci</i></label></b></span>&nbsp;-&nbsp;<b>$
                                                                        <span id="pjournallabel">20</span></b></td>

                                                            <td vAlign="bottom" align="right"><strong>$</strong>
                                                                  <input name="TextBox1" type="text" size="2" readonly="readonly" id="TextBox1" /></td>
                                                      </tr>
                                                </table>
0
Comment
Question by:trevoray
  • 5
  • 5
  • 4
  • +3
18 Comments
 

Author Comment

by:trevoray
Comment Utility
ok, i was a } in each function. i added those and it now works partial. if elective = true; therefore there are two checkboxes, and the user clicks on the first checkbox, it will correctly place the correct value in the textbox. however if the user clicks on the second checkbox, the value in the textbox is not changed.
0
 
LVL 10

Expert Comment

by:Bustarooms
Comment Utility
you can probably come up with better code to do all of this....but if you just want your code fixed use what i did below.
you need to add up your values before you do eval()


--------------------------------------------------------------------------------
function ejournals_onclick(pjournalprice,ejournalprice,elective)
         {
         var pcks=document.Form1.elements['Checkbox1']
         var ecks=document.Form1.elements['Checkbox2']
         
         var txt=document.Form1.elements['TextBox1']
         var pcost=pjournalprice
         var ecost=ejournalprice

var tempVal;
         
         if (ecks.checked != true)
         {
         tempVal =  0;
         pcks.checked = false;
         }
         else
         {
         tempVal = eval(ecost);
         pcks.checked = false;
         }
        txt.value = eval(tempVal)
         }
         
         function pjournals_onclick(pjournalprice,ejournalprice,elective)
         {
         var pcks=document.Form1.elements['Checkbox1']
         var ecks=document.Form1.elements['Checkbox2']
         
         var txt=document.Form1.elements['TextBox1']
         var pcost=pjournalprice
         var ecost=ejournalprice

var tempVal;
         
         if (elective != 'true')
         {
               if (pcks.checked != true)
              {
              txt.value =  0;
              }
              else
              {
              txt.value = eval(pcost);
              }
         else
         {
              if (pcks.checked == true)
               {
              tempVal = pcost + ecost;
              ecks.checked = true;
              }
              if (pcks.checked == false && ecks.checked == true)
              {
              tempVal = ecost;
              }
              if (pcks.checked == false && ecks.checked == false)
              {
              tempVal = 0
              }
         }
        txt.value = eval(tempVal)
         }
0
 
LVL 6

Expert Comment

by:ren_b
Comment Utility
well even then, is that what its supposed to do? cause i have it "working" but when you check the first box, it doesn't check but puts a value of 50 in the box, then if you check the second box, it sets the value to 70, but checks the first box, and then if you click the first box again, it sets the value to 0. you really need to work out the logic better.
0
 

Author Comment

by:trevoray
Comment Utility
bustarooms, i tried your code, and now it doesn't work at all.
0
 

Author Comment

by:trevoray
Comment Utility
ren_b, please don't lecture me. the reason i am on here is because i need help. if you'd like to help, i'd very much appreciate it, but there's no need for you tone.
0
 
LVL 10

Expert Comment

by:Bustarooms
Comment Utility
well then, if you wanted to re-work the entire thing, I would probably do it like this


<html>
<head>
<script language="Javascript">
function calculate(theForm){
   var total=0;  
   if(theForm.eSub != null && theForm.eSub.checked)
      total += 20;
   if(theForm.pSub != null && theForm.pSub.checked)
       total += 70;
 theForm.TextBox1.value = total;
}
</script>
</head>
<body>
<form>
<input type="textbox" name="TextBox1"><br>
Electronic Subscription: <input type="checkbox" name="eSub" onclick="calculate(this.form);"><br>
Print Subscription: <input type="checkbox" name="pSub" onclick="calculate(this.form);"><br>
</form>
</body>
</html>


i am not sure what your deal was with the elective=true

that script above totals up if the checkbox is checked AND if it is not null.  if the esubscription does not exist on the page, it does not try to add it up and wont throw an error
0
 
LVL 31

Expert Comment

by:GwynforWeb
Comment Utility
try this

<script>
function update(){
if ((document.f1.Checkbox2.checked) && (document.f1.Checkbox1.checked)) document.f1.Textbox1.value=70
else
if ( (document.f1.Checkbox1.checked)) document.f1.Textbox1.value=20
}
</script>


<form name="f1">
  <p><input name="Checkbox1" type="checkbox" onclick="update()" value="ON">Electronic
  Subscription to </p>
  <p><input name="Checkbox2" type="checkbox" n onclick="update()" value="ON">Add Print
  Subscription to </p>
  <p><input name="Textbox1" type="text" size="2" readonly="readonly" /></p>
</form>
0
 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
Here my version:

<html>
<head>
<script>
function ejournals_onclick(pjournalprice,ejournalprice,elective) {
  var pcks=document.Form1.CheckBox1;
  var ecks=document.Form1.Checkbox2;
 
  var txt=document.Form1.elements['TextBox1']
  var pcost=pjournalprice
  var ecost=ejournalprice
 
  if (ecks.checked != true){
    txt.value =  0;
    pcks.checked = false;
  } else {
    txt.value = ecost;
    pcks.checked = false;
  }
}
 
function pjournals_onclick(pjournalprice,ejournalprice,elective) {
  var pcks=document.Form1.CheckBox1;
  var ecks=document.Form1.Checkbox2;
 
  var txt=document.Form1.TextBox1;
  var pcost=pjournalprice
  var ecost=ejournalprice
 
  if (elective != 'true'){
    if (pcks.checked != true) {
      txt.value =  0;
    } else {
      txt.value = eval(pcost);
    }
  } else {
    if (pcks.checked == true)  {
      txt.value = eval(pcost) + eval(ecost);
      ecks.checked = true;
    }
    if (pcks.checked == false && ecks.checked == true) {
      txt.value = eval(ecost);
    }
    if (pcks.checked == false && ecks.checked == false) {
      txt.value = 0
    }
  }
}
</script>
</head>
<body>
<form name="Form1">
                <table cellSpacing="0" cellPadding="0" width="100%" border="0">
              <tr>
            <td>
                 <span><b><input id="Checkbox2" type="checkbox" name="Checkbox2" onclick="javascript:ejournals_onclick('20','50','true');" /><label for="Checkbox2">Electronic Subscription to <i>ToxSci</i></label></b></span>&nbsp;-
                 <b>$
               <span id="ejournallabel">50</span></b></td>

            <td vAlign="bottom" align="right">&nbsp;</td>
              </tr>
                </table>
           
    </td></tr></table>
           <table cellSpacing="0" cellPadding="0" width="100%" border="0">
                <tr>
              <td>
            <span><b><input id="CheckBox1" type="checkbox" name="CheckBox1" onclick="javascript:pjournals_onclick('20','50','true');" /><label for="CheckBox1">Add Print Subscription to <i>ToxSci</i></label></b></span>&nbsp;-&nbsp;<b>$
                 <span id="pjournallabel">20</span></b></td>

              <td vAlign="bottom" align="right"><strong>$</strong>
            <input name="TextBox1" type="text" size="2" readonly="readonly" id="TextBox1" value="0" /></td>
                </tr>
           </table>
</form>
</body>
</html>


0
 

Author Comment

by:trevoray
Comment Utility
bustarooms, thanks! wow that is much more efficient. the reason that i need the elective="true" is because if there is only one checkbox (elective <> "true") then the value of that checkbox will be the print journal price (a variable), if there are two checkboxes (elective = "true") then the value of the textbox will be the print journal price (variable) + the electronic journal price (variable), so that's why i have to pass the prices and elective value through the function.

so, with all that, i am not sure that i can simplify my code.  or can i?

thanks!
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 10

Accepted Solution

by:
Bustarooms earned 250 total points
Comment Utility
honestly, i am trying to get the elective thing but am still not 100% sure

look at the following... now you can pass the price to the function, whatever it may be, with the onclick

-----------------  one checkboxes -----------------------
<html>
<head>
<script language="Javascript">
function calculate(){

var theForm, pSubPrice, eSubPrice;

  for(i=0;i<arguments.length;i++){
    if(i == 0)
      theForm = arguments[0]
    if(i == 1)
      pSubPrice = arguments[1]
    if(i == 2)
      eSubPrice = arguments[2]  

  }

   var total=0;  
   if(theForm.eSub != null && theForm.eSub.checked)
      total += eSubPrice;
   if(theForm.pSub != null && theForm.pSub.checked)
       total += pSubPrice;
 theForm.TextBox1.value = total;
}
</script>
</head>
<body>
<form>
<input type="textbox" name="TextBox1"><br>
Print Subscription: <input type="checkbox" name="pSub" onclick="calculate(this.form,70,20);"><br>
Electronic Subscription: <input type="checkbox" name="eSub" onclick="calculate(this.form,70,100);"><br>
</form>
</body>
</html>


-----------------  two checkboxes -----------------------
<html>
<head>
<script language="Javascript">
function calculate(){

var theForm, pSubPrice, eSubPrice;

  for(i=0;i<arguments.length;i++){
    if(i == 0)
      theForm = arguments[0]
    if(i == 1)
      pSubPrice = arguments[1]
    if(i == 2)
      eSubPrice = arguments[2]  

  }

   var total=0;  
   if(theForm.eSub != null && theForm.eSub.checked)
      total += eSubPrice;
   if(theForm.pSub != null && theForm.pSub.checked)
       total += pSubPrice;
 theForm.TextBox1.value = total;
}
</script>
</head>
<body>
<form>
<input type="textbox" name="TextBox1"><br>
Print Subscription: <input type="checkbox" name="pSub" onclick="calculate(this.form,70);"><br>
</form>
</body>
</html>
0
 
LVL 10

Expert Comment

by:Bustarooms
Comment Utility
those are backwards by the way,   the first is with two checkboxes and the seconds is the same exact code but with only 1 checkbox
0
 
LVL 31

Expert Comment

by:GwynforWeb
Comment Utility
change the function to bleow ( am I undestanding you problem correctly)

<script>
function update(){
document.f1.Textbox1.value=0
if ((document.f1.Checkbox2.checked) && (document.f1.Checkbox1.checked)) document.f1.Textbox1.value=70
else
if ( (document.f1.Checkbox1.checked)) document.f1.Textbox1.value=20
}
</script>
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
Well I hope this does it for you.  I tried to keep your variable names when possible.  I'm not sure why it wouldn't let me set ecks = document.Form1.Checkbox2
or any of the variables for that matter to an object.

It might be because of the table, but anyways it really isn't necessary (ya it makes it shorter and if you are reusing it then shorter is nice).

I am not trying to lecture you, but you really should try to follow some naming conventions when putting name's and id's to objects.  Also if you ask more questions, try to format the code so it is nice and easy to cut and paste (i.e. I shouldn't have to check for missing brackets or extra HTML tags in your code which I did.).  I'm no professional, but it makes it easier for people to help you out.

Anyways, I ran this piece of code in Dreamweaver and it should work fine for you.

<html>
<head>
<script language="JavaScript">
//Your original variables
var pcost = 20, ecost = 50;

var subPrice = 0;            //Sum to hold total price
var eClicked = 0;            //Value to multiply electronic subscription by
var pClicked = 0;            //Value to multiply print subscription by

function ejournals_onclick()
{
      //Set multiplier for electronic subscription
      eClicked=(document.Form1.Checkbox2.checked != true)?0:1
      calcSubPrice();
}
         
function pjournals_onclick()
{
      //Set multiplier for electronic subscription
      pClicked=(document.Form1.CheckBox1.checked != true)?0:1
      calcSubPrice();
}        

function calcSubPrice()
{
      //Set the subscription price
      subPrice = (pClicked * pcost) + (eClicked * ecost);
      document.Form1.TextBox1.value = subPrice;
}  

</script>
</head>

<body>
<form name="Form1">
<table cellSpacing="0" cellPadding="0" width="100%" border="0">
      <tr>
            <td>
                  <span><b><input id="Checkbox2" type="checkbox" name="Checkbox2" onclick="ejournals_onclick()" /><label for="Checkbox2">Electronic Subscription to <i>ToxSci</i></label></b></span>&nbsp;-
                  <b>$
                  <span id="ejournallabel">50</span></b>
            </td>
            <td vAlign="bottom" align="right">&nbsp;</td>
      </tr>
</table>
<table cellSpacing="0" cellPadding="0" width="100%" border="0">
      <tr>
            <td>
                  <span><b><input id="CheckBox1" type="checkbox" name="CheckBox1" onclick="pjournals_onclick()" /><label for="CheckBox1">Add Print Subscription to <i>ToxSci</i></label></b></span>&nbsp;-&nbsp;<b>$
                  <span id="pjournallabel">20</span></b>
            </td>
            <td vAlign="bottom" align="right">
                  <strong>$</strong><input name="TextBox1" type="text" size="2" readonly="readonly" id="TextBox1" value="0"/>
            </td>
      </tr>
</table>
</form>
</body>
</html>

I hope this is what you were looking for.

Oh, in case you don't know the line

pClicked=(document.Form1.CheckBox1.checked != true)?0:1

is just a conditional statement that is equivalent to a simple if-then-else statement as such:

if (document.Form1.CheckBox1.checked != true)
{
     pClicked = 0;
}
else
{
     pClicked = 1;
}

Have a nice day!

WarCrimes
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
I don't know how you are deciding to hide or show the checkbox for Electronic Subscriptions, but all you need to do is set eClicked = 0 when you hide it.  That will keep it from being added to the total.
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
Sorry to add yet another comment.  I forgot to explain my code though.

You'll notice the Javascript is much, much shorter.  It's also been abstracted so you don't have to pass any variables.  You simply set the price values for the subscriptions in one place (when they are initialized).  This will make it easier to CHANGE the prices as well and not worry about messing up the code.  It should be very easy now to add even more subscriptions to this if you want to.  

In the HTML, I'm not real sure about using the table the way you do, and you were missing the <form> tags so I just threw those in.  You may want to move some things around or re-design the HTML, but as long as you put the function call in the onClick attribute for each checkbox it should work fine.

Enjoy.

WarCrimes
0
 
LVL 18

Assisted Solution

by:WarCrimes
WarCrimes earned 250 total points
Comment Utility
The last comment --- I PROMISE!

This Javascript is even more efficient than the previous one I posted.

<script language="JavaScript">
//Your original variables
var pcost = 20, ecost = 50;

var subPrice = 0;            //Sum to hold total price

function ejournals_onclick()
{
      //Set multiplier for electronic subscription
      eClicked=(document.Form1.Checkbox2.checked != true)?subPrice -= ecost:subPrice += ecost
      printSubPrice();
}
         
function pjournals_onclick()
{
      //Set multiplier for electronic subscription
      pClicked=(document.Form1.CheckBox1.checked != true)?subPrice -= pcost:subPrice += pcost
      printSubPrice();
}    

function printSubPrice()
{
      //Set the total subscription price
      document.Form1.TextBox1.value = subPrice;
}  
</script>

The lines like

 eClicked=(document.Form1.Checkbox2.checked != true)?subPrice -= ecost:subPrice += ecost

should be on one line.

WarCrimes
0
 

Author Comment

by:trevoray
Comment Utility
thanks warcrimes! thanks for the suggestions about my naming, i am still learning. i'm going to split points between you and busta
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
Thank you, and your welcome.  I am still learning myself (had some good teachers in the past), so it's nice to be able to help out.  I've been on the other side many times.

Oh and by the way, in my last posting for the javascript.  You might want to clean that up a little.  The comments for setting a multiplier are no longer correct, and you can just delete the eClicked= and pClicked= so it looks like

(document.Form1.CheckBox1.checked != true)?subPrice -= pcost:subPrice += pcost

WarCrimes
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

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

10 Experts available now in Live!

Get 1:1 Help Now