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?
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> ';
for (var j=0; j<Responses.length; j++) {
str += '<input type="radio" name="R'+i+'" value="'+Responses.charAt(j)+'" /> ';
str += Responses.charAt(j)+' ';
}
str += '<p />';
}
document.write(str);
</script>
<input type="submit" value="Submit" title="Submit" />
<input type="reset" value="Reset" title="Reset" />
</div><!-- form -->
</form>
</div><!-- center -->
</div>
<!-- Page Footer -->
<div id="footer">
<br clear="all" /><hr />
Written on June 12, 2012, by:
<a href="mailto:jalarie@umich.edu">James Alarie</a>.
Modified by: jmrker
</div>
</div>
</body>
</html>
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.
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.
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.
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.
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.
<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>
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?
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 07:59 PM.
Reason: "borrowed" jalarie's idea for values for the radios :D
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.
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.
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>
Bookmarks