www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: How do I use JavaScript to calculate forms

  1. #1
    Join Date
    Jun 2012
    Posts
    14

    How do I use JavaScript to calculate forms

    I learned BASIC programming back in the Stone Age with an AppleIIc and Commodore 64. Iíve taught myself enough html to know how to design simple web pages, but I want to design an interactive website. My health is not good so I donít have the physical stamina to learn anything complicated, and JavaScript seems to be the only language that I can use on a webpage without having to buy/download software or make alterations to my computer that I donít have the patience to learn how to do.

    I have 3 different how-to books plus a how-to video and Iíve been to ever website I can find and I still donít know if JavaScript can even be used to do what I want my website to do. My ultimate aim is to design an online (or at least an offline but html-based) presidential election game. But right now I am trying to create a survey form that will determine peopleís political ideology. I have 13 questions and each question can have 1 of 6 possible answers a to f. I can design a form with radio button well enough with html, but I cannot figure out how to use JavaScript to calculate the surveyís results. Each possible answer, a to f, for each question represents a location on the political spectrum. So I need to add up how many times a survey-taker clicks on an answer for a given letter. Iíve tried using onclick, but all of the examples I can find on the net are for text alerts saying whether or not an answer is correct. But my survey has no ďcorrectĒ answers. I just need to keep a running total of how many a-answers, how many b-answers, how many c-answers and so on are given and then tell the survey-taker what his results are. What else could I use?

  2. #2
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    598
    Start with the following, try it as-is, add the 3 through 13 items where indicated, try it out the result:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
      <head>
    
        <title>Calculate Forms</title>
    <!--- http://www.webdeveloper.com/forum/showthread.php?t=261564 --->
    
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="Content-Language" content="en-US" />
        <meta name="Author" content="James Alarie - jalarie@umich.edu" />
        <meta name="description" content="How to Calculate Forms." />
        <meta name="keywords" content="calculate,form" />
        
        <link rel="icon" href="favicon.ico" />
        <link rev="made" href="mailto:jalarie@umich.edu" />
        
    <!--
        Author:    James Alarie
        Company:   -independent-
        Address:   3391 N Genesee Rd
                   Flint  MI  48506
                   Latitude: 42.9663  Longitude: -83.7769
        Telephone: +1-810-736-8259
        Fax:       -none-
        Web Site:  http://spruce.flint.umich.edu/~jalarie/
        E-Mail:    jalarie@umich.edu
        Comments:  Having said that, I've probably told you more than I know.
    -->
    
        <link href="style1.css" rel="stylesheet" type="text/css" />
        <style type="text/css">
          /*<![CDATA[*/
          /*]]>*/
        </style>
        
        <script type="text/javascript" src="style1.js"></script>
        <script type="text/javascript">
          /*<![CDATA[*/
    
      function CalcIt() {
        f1=document.forms[0];                           // abbreviation
        R1V='';
        R2V='';
    // add R3V through R13V here
        aCount=0;
        bCount=0;
        cCount=0;
        dCount=0;
        eCount=0;
        fCount=0;
        for (ix1=0; ix1< f1.R1.length; ix1++) {
          if (f1.R1[ix1].checked) {
            R1V=f1.R1[ix1].value;
          }
        }
        for (ix1=0; ix1< f1.R2.length; ix1++) {
          if (f1.R2[ix1].checked) {
            R2V=f1.R2[ix1].value;
          }
        }
    // add 3 through 13 'for ...' sets of 5 lines each here
        if (R1V == 'a') { aCount+=1; }
        if (R1V == 'b') { bCount+=1; }
        if (R1V == 'c') { cCount+=1; }
        if (R1V == 'd') { dCount+=1; }
        if (R1V == 'e') { eCount+=1; }
        if (R1V == 'f') { fCount+=1; }
        if (R2V == 'a') { aCount+=1; }
        if (R2V == 'b') { bCount+=1; }
        if (R2V == 'c') { cCount+=1; }
        if (R2V == 'd') { dCount+=1; }
        if (R2V == 'e') { eCount+=1; }
        if (R2V == 'f') { fCount+=1; }
        Out ='';
        Out+='a='+aCount+'\n';
        Out+='b='+bCount+'\n';
        Out+='c='+cCount+'\n';
        Out+='d='+dCount+'\n';
        Out+='e='+eCount+'\n';
        Out+='f='+fCount+'\n';
        alert(Out);
        return true;
      } CalcIt
    
          /*]]>*/
        </script>
    
      </head>
    
      <body class="body1">
       <div id="body">
    <!-- Page Header -->
        <div id="header">
          <h1>Calculate Forms</h1>
          <hr />
        </div>
    
    <!-- Content -->
        <div id="content">
          <br />
          <noscript>
            <p class="notice">
              You must have scripting enabled to make full use of this page.
            </p>
          </noscript>
          
          <div class="center">
            <form method="post" action="javascript:void(0);" onsubmit="CalcIt();">
             <div class="form">
              <label for="Q1">Question 1:</label>&nbsp;&nbsp;
              <input type="radio" name="R1" value="a" /> a&nbsp;&nbsp;
              <input type="radio" name="R1" value="b" /> b&nbsp;&nbsp;
              <input type="radio" name="R1" value="c" /> c&nbsp;&nbsp;
              <input type="radio" name="R1" value="d" /> d&nbsp;&nbsp;
              <input type="radio" name="R1" value="e" /> e&nbsp;&nbsp;
              <input type="radio" name="R1" value="f" /> f&nbsp;&nbsp;
              <br />
              <label for="Q2">Question 2:</label>&nbsp;&nbsp;
              <input type="radio" name="R2" value="a" /> a&nbsp;&nbsp;
              <input type="radio" name="R2" value="b" /> b&nbsp;&nbsp;
              <input type="radio" name="R2" value="c" /> c&nbsp;&nbsp;
              <input type="radio" name="R2" value="d" /> d&nbsp;&nbsp;
              <input type="radio" name="R2" value="e" /> e&nbsp;&nbsp;
              <input type="radio" name="R2" value="f" /> f&nbsp;&nbsp;
              <br />
    <!-- add Q3 through Q13 sets of 8 lines each here -->
              <input type="submit" value="Submit" title="Submit" />&nbsp;
              <input type="reset" value="Reset" title="Reset" />&nbsp; 
             </div><!-- form -->
            </form>
            
          </div><!-- center -->
      
        </div>
      
    <!-- Page Footer -->
        <div id="footer">
          <br clear="all" /><hr />
          Written on June 12, 2012, by:&nbsp;
          <a href="mailto:jalarie@umich.edu">James Alarie</a>.
        </div>
    
       </div>
      </body>
    
    </html>

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,413

    Lightbulb

    Moderate modification to 'jalarie's code.
    Should make it easier to add more questions without making the code so redundant.
    I find I make fewer mistakes when I type the least.
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
      <head>
    
        <title>Calculate Forms</title>
    <!--- http://www.webdeveloper.com/forum/showthread.php?t=261564 --->
    
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="Content-Language" content="en-US" />
        <meta name="Author" content="James Alarie - jalarie@umich.edu" />
        <meta name="description" content="How to Calculate Forms." />
        <meta name="keywords" content="calculate,form" />
        
        <link rel="icon" href="favicon.ico" />
        <link rev="made" href="mailto:jalarie@umich.edu" />
        
    <!--
        Author:    James Alarie
        Company:   -independent-
        Address:   3391 N Genesee Rd
                   Flint  MI  48506
                   Latitude: 42.9663  Longitude: -83.7769
        Telephone: +1-810-736-8259
        Fax:       -none-
        Web Site:  http://spruce.flint.umich.edu/~jalarie/
        E-Mail:    jalarie@umich.edu
        Comments:  Having said that, I've probably told you more than I know.
    -->
    
        <link href="style1.css" rel="stylesheet" type="text/css" />
        <style type="text/css">
          /*<![CDATA[*/
          /*]]>*/
        </style>
        
        <script type="text/javascript" src="style1.js"></script>
        <script type="text/javascript">
          /*<![CDATA[*/
    
    function getRBtnName(GrpName) {
      var sel = document.getElementsByName(GrpName);
      var fnd = -1;
      var str = '';
      for (var i=0; i<sel.length; i++) {
        if (sel[i].checked == true) { str = sel[i].value;  fnd = i; }
      }
    //  return fnd;   // return option index of selection
    // comment out next line if option index used in line above  
      return str;
    } 
    var Questions = [
       'Question 1',
       'Question 2',
       'Question 3',
       'Question 4',
       'Question 5',
       'Question 6',
       'Question 7',
       'Question 8',
       'Question 9',
       'Question 10',
       'Question 11',
       'Question 12',
       'Question 13',
    ];
    var Responses = 'abcdef';
    var Counts = [0,0,0,0,0,0,0,0,0,0,0,0,0];
    
      function CalcIt() {
        Counts = [0,0,0,0,0,0,0,0,0,0,0,0,0];
        var resp = '';
        for (var i=0; i<Questions.length; i++) {
          resp = getRBtnName('R'+i);
          if (resp != '') {
            posn = Responses.indexOf(resp);
            Counts[posn]++;
          }
        }
        Out ='';
        for (var i=0; i<Responses.length; i++) {
          Out += Responses.charAt(i)+' = '+Counts[i]+'\n';
        }
        alert(Out);
        return true;
      } // CalcIt
    
          /*]]>*/
        </script>
    
      </head>
    
      <body class="body1">
       <div id="body">
    <!-- Page Header -->
        <div id="header">
          <h1>Calculate Forms</h1>
          <hr />
        </div>
    
    <!-- Content -->
        <div id="content">
          <br />
          <noscript>
            <p class="notice">
              You must have scripting enabled to make full use of this page.
            </p>
          </noscript>
          
          <div class="center">
            <form method="post" action="javascript:void(0);" onsubmit="CalcIt();">
             <div class="form">
    
    <script type="text/javascript">
    var str = '';
    for (var i=0; i<Questions.length; i++) {
      str += '<label for="Q'+i+'">'+Questions[i]+':</label>&nbsp;&nbsp;';
      for (var j=0; j<Responses.length; j++) {
        str += '<input type="radio" name="R'+i+'" value="'+Responses.charAt(j)+'" /> ';
        str += Responses.charAt(j)+'&nbsp;&nbsp;';
      }
      str += '<p />';
    }
    document.write(str);
    </script>
    
              <input type="submit" value="Submit" title="Submit" />&nbsp;
              <input type="reset" value="Reset" title="Reset" />&nbsp; 
             </div><!-- form -->
            </form>
          </div><!-- center -->
        </div>
      
    <!-- Page Footer -->
        <div id="footer">
          <br clear="all" /><hr />
          Written on June 12, 2012, by:&nbsp;
          <a href="mailto:jalarie@umich.edu">James Alarie</a>.
          Modified by: jmrker
        </div>
    
       </div>
      </body>
    
    </html>

  4. #4
    Join Date
    Jun 2012
    Posts
    14
    I got the email for your reply late this evening. Iíve started putting your script and my text together and I tried the first question and it seems to work OK. Iíll finish tomorrow and let you know how it turns out.

  5. #5
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    598
    Quote Originally Posted by JMRKER View Post
    Moderate modification to 'jalarie's code.
    Should make it easier to add more questions without making the code so redundant. I find I make fewer mistakes when I type the least. ;)
    I agree with you. My reason for not doing it that way to begin with was to keep it as easy as possible for a new programmer to understand. Do it the basic messy way a few times and then learn to do it better.

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,413

    Arrow

    Quote Originally Posted by jalarie View Post
    I agree with you. My reason for not doing it that way to begin with was to keep it as easy as possible for a new programmer to understand. Do it the basic messy way a few times and then learn to do it better.
    No problem.

    I could just see this script covering several pages to check for typos as questions were added.
    Sometimes, for a beginner, you get lost in a forest of code.
    Better for OP to ask "why?" the shorter version than to search through a lot of similar code when the 'copy/paste' operation has gotten out of control.

  7. #7
    Join Date
    Jun 2012
    Posts
    14
    Quote Originally Posted by jalarie View Post
    Start with the following, try it as-is, add the 3 through 13 items where indicated, try it out the result:
    Iíve added all the questions and the all of the 3-13 code you said to add, but no matter how many a or b answers I give the program will not calculate a score higher than 2 for the a or b answer and it will not calculate anything but 0 for any of the other answers c-f.

    Having seen the amount of code that will take to do this one survey I can tell that it wonít be worth my or anyone elseís time and effort to try to write the code for the game I want to design. BASIC programming from 30 years ago (roughly todayís Quickbasic) could do this survey with a fraction of the amount of written code and it would do it a much more straightforward manner. But nobody today would want a computer game that has no better than VGA graphics, and my understanding is that the old version of BASIC cannot be used in a web setting.

  8. #8
    Join Date
    Jun 2012
    Posts
    14
    I have 3 how-to books for JavaScript checked out from the library right now and no 2 of them present things in the same order. One book talks about functions before it talks about arithmetic operations so the reader doesnít know enough about what JavaScript can do to know any code that could be used in a function. And Iíve yet to find anything in any of these books that would be the equivalent of a BASIC input statement. And the books I seen for Python and PHP are the same way. I think computer books written since 1990 have all been written by people with ADHD. I donít see how computer book writers havenít all gone insane.

  9. #9
    Join Date
    Nov 2010
    Posts
    1,090
    another possibility, by another ADHD coder

    Code:
    <body>        
    <script type="text/javascript">		
    var answers = {a:0,b:0,c:0,d:0,e:0,f:0,g:0};
    		
    for (var i = 0; i < 10; i++) {
    document.body.appendChild(document.createTextNode("Question "+(i+1)+" "))
    for (a in answers) {
    inp=document.createElement("input");
    inp.type="radio";
    inp.name="radio"+i;
    inp.id="radio"+i+a;
    var label = document.createElement("label")
    label.htmlFor = inp.id;
    label.appendChild(document.createTextNode(a));
    document.body.appendChild(label);
    document.body.appendChild(inp);
    		}
    document.body.appendChild(document.createElement("br"))		
    	}	
    	
    function checkIt(){
    inps=document.getElementsByTagName("input")
    for (var i = 0; i < inps.length; i++) {
    if (inps[i].type=="radio"&&inps[i].checked){
    lett=inps[i].previousSibling.innerHTML;
    answers[lett]++
    		}
    	}
    str=""
    	for (i in answers){
    str+= i+ " :"+answers[i]+"\n"
    }
    alert(str)
    }
    	</script>
    <input type="button" value="check scores" onclick="checkIt()">		
    </body>

  10. #10
    Join Date
    Jun 2012
    Posts
    14
    Saving the JavaScript code- which does not work- with my questions and answers as an MS Word document takes 87KB of disk space and covers 13 pages.

    Saving a Liberty BASIC program- that does work- also with my questions and answers as an MS Word document takes only 45kb of disk space and covers only 6 pages.

    I spent more time formatting my questions and answers, which I already had written in MS Word, to make them into data statements that Liberty Basic could use than I did writing the Liberty Basic program.

    There is a version of Liberty Basic that is supposed to be useable with webpages, but the sale price is more than I want to spend to start a project that I may not be able to finish due to my health.

    Would it possible to use a loop with document.write statements for JavaScript and ask the questions one at a time and add up the answers as they are given- essentially make a JavaScript program that acts like a BASIC program? Can a web user input data for a JavaScript program without using a form?

  11. #11
    Join Date
    Jun 2012
    Posts
    14
    Quote Originally Posted by xelawho View Post
    another possibility, by another ADHD coder
    This has considerablly less code, but how do I put my surveyís questions and answers into it?

  12. #12
    Join Date
    Nov 2010
    Posts
    1,090
    I just made 5 questions - you get the idea. You can just keep adding them to the array. You said that your answers were all A to F, though?
    Code:
    <body>        
    <script type="text/javascript">		
    var answers = {a:0,b:0,c:0,d:0,e:0,f:0};
    var questions=["How well do you know the cadidate?",
    "How well do you trust the cadidate?",
    "Do you agree with cadidate's health care policy?",
    "Would you vote for the candidate if he were gay?",
    "Do you think the candidate will fulfill his campaign promises?"] 
    		
    for (var i = 0; i < questions.length; i++) {
    document.body.appendChild(document.createTextNode(questions[i]+" "));
    for (a in answers) {
    inp=document.createElement("input");
    inp.type="radio";
    inp.name="radio"+i;
    inp.value=a;
    document.body.appendChild(document.createTextNode(a));
    document.body.appendChild(inp);
    		}
    document.body.appendChild(document.createElement("br"))		
    	}	
    	
    function checkIt(){
    inps=document.getElementsByTagName("input")
    for (var i = 0; i < inps.length; i++) {
    if (inps[i].type=="radio"&&inps[i].checked){
    lett=inps[i].value;
    answers[lett]++
    		}
    	}
    str=""
    	for (i in answers){
    str+= i+ " :"+answers[i]+"\n"
    }
    alert(str)
    }
    	</script>
    <input type="button" value="check scores" onclick="checkIt()">		
    </body>
    Last edited by xelawho; 06-13-2012 at 08:59 PM. Reason: "borrowed" jalarie's idea for values for the radios :D

  13. #13
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,413

    Question

    Quote Originally Posted by homewardbound View Post
    This has considerablly less code, but how do I put my surveyís questions and answers into it?
    If this project is taking so much memory and printout, how about showing what you are using. You have been provided 3 acceptable scripts for modification, but you have yet to provide what you are testing with nor any indications as to what the errors are that you are receiving.

    Show a link or provide some code that is giving you fits.

    Note: If you are saving your scripts with MS Word, make sure you are saving as a text document, not .doc or .docx format. Also the text should be saved with an .html extension for testing in whatever browser you are using.

  14. #14
    Join Date
    Jun 2012
    Posts
    14
    Quote Originally Posted by xelawho View Post
    I just made 5 questions - you get the idea. You can just keep adding them to the array. You said that your answers were all A to F, though?
    What happens when the answers change for each question? I will still need to add up all of the A answers and all of the B answers and so on, but the A, B, C, D, E, and F answers will change for each question. I can see that this code generates the radio button for each question, but how can I add different text to each button for each question? For example:


    Question 1: What is your view of property?
    A. Most property should be privately owned as a life-trust, but since property equals power society has a right to regulate private property to insure that it is acquired by honest means; that is not used in ways that brings harm to or infringe on the rights of others and that it is used in ways that insure its usefulness to future generations.

    B. All property should be privately owned and individuals have a right to acquire and use property as they see fit without regulation of any kind so that they may maximize their own material benefit.

    C. Most property should be privately owned, but society has an obligation to regulate private property to the extent necessary to insure that no segment of society is lacking in essential material security- food, shelter, healthcare, education, et cetera.

    D. Most property should be privately owned, but the government has an obligation to regulate private property to insure that it is used in a way that benefits the nation-state.

    E. Most property should be publicly owned to insure that all segments of society have adequate material possessions before anybody has an excess.

    F. Private property must not exist and every member of society has an obligation to labor as much as they can in order to insure that everyone in society has their material needs met.

  15. #15
    Join Date
    Nov 2010
    Posts
    1,090
    right. in that case it would make sense to store your questions and answers in objects, put them in an array and loop through them. This one outputs numbers instead of letters (lazy coding, but makes it simpler) - that's OK isn't it?

    Code:
    <body>        
    <script type="text/javascript">		
    
    var questions=[{que:"What is your view of property?",ans:["A. Most property should be privately owned as a life-trust, but since property equals power society has a right to regulate private property to insure that it is acquired by honest means; that is not used in ways that brings harm to or infringe on the rights of others and that it is used in ways that insure its usefulness to future generations.",
    "B. All property should be privately owned and individuals have a right to acquire and use property as they see fit without regulation of any kind so that they may maximize their own material benefit.",
    "C. Most property should be privately owned, but society has an obligation to regulate private property to the extent necessary to insure that no segment of society is lacking in essential material security- food, shelter, healthcare, education, et cetera.",
    "D. Most property should be privately owned, but the government has an obligation to regulate private property to insure that it is used in a way that benefits the nation-state.",
    "E. Most property should be publicly owned to insure that all segments of society have adequate material possessions before anybody has an excess.",
    "F. Private property must not exist and every member of society has an obligation to labor as much as they can in order to insure that everyone in society has their material needs met."]}] 
    		
    for (var i = 0; i < questions.length; i++) {
    document.body.appendChild(document.createTextNode(questions[i].que+" "));
    document.body.appendChild(document.createElement("br"))	
    for (var a = 0; a < questions[i].ans.length; a++) {
    inp=document.createElement("input");
    inp.type="radio";
    inp.name="radio"+i;
    inp.value=a;
    document.body.appendChild(inp);
    document.body.appendChild(document.createTextNode(questions[i].ans[a]));
    document.body.appendChild(document.createElement("br"))	
    		}
    document.body.appendChild(document.createElement("br"))		
    	}	
    	
    function checkIt(){
    var answers = {0:0,1:0,2:0,3:0,4:0,5:0};
    var inps=document.getElementsByTagName("input")
    for (var i = 0; i < inps.length; i++) {
    if (inps[i].type=="radio"&&inps[i].checked){
    var num=inps[i].value;
    answers[num]++
    		}
    	}
    str=""
    for (i in answers){
    str+= i+ " :"+answers[i]+"\n"
    }
    alert(str)
    }
    	</script>
    <input type="button" value="check scores" onclick="checkIt()">		
    </body>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles