Keeping score in javascript - javascript

I am trying to develop a simple online word game using Javascript. I'm have way through, but I'm stuck at the moment. Basically the first part of the game is to display ten words and it's description.
Then users can click the "test me" button and will be directed to a page I called testme.html where I will show a description, and then, four words they could choose from. I have the description working fine once a player clicks the button the next description appears. Now, I need to be able to switch around the multiple choices as well, and also create a function where I could see if they picked the right or wrong word and then at the end I could display how many they got right or wrong for example: you got 9/10 right.
Here is the main page: http://alexallin.com/wordgame/
Here is the testme.html page: http://alexallin.com/wordgame/Testme.html
var ThisText = 0;
var Words = [ { word: '1. Amicable', definition: 'friendly, agreeable.' },
{ word: '2. acumen', definition: 'the ability to make good judgments and quick decisions, typically in a particular domain.' },
{ word: '3. accoutrements', definition: 'additional items of dress or equipment, or other items carried or worn by a person or used for a particular activity.' },
{ word: '4. Abstinence', definition: 'the act of refraining from pleasurable activity, e.g., eating or drinking.' },
{ word: '5. Adulation', definition: 'high praise.' },
{ word: '6. Adversity', definition: 'misfortune, an unfavorable turn of events.' },
{ word: '7. Aesthetic', definition: 'pertaining to beauty or the arts.' },
{ word: '8. Anachronistic', definition: 'out-of-date, not attributed to the correct historical period.' },
{ word: '9. Anecdote', definition: 'short, usually funny account of an event.' },
{ word: '10. Antagonist', definition: 'foe, opponent, adversary.' },
];
function ChangeWordTo(NextWord) {
document.getElementById('Answer_Box_One').innerHTML = NextWord;
}
// this grabs the ID description
function ChangeDescriptionTo(NextDescription) {
document.getElementById('description').innerHTML = NextDescription;
}
// This loads it to the first definition...
function onLoad() {
switchTo(0);
}
// won't work with out
function switchTo(which) {
ChangeWordTo(Words[which].word);
ChangeDescriptionTo(Words[which].definition);
}
// This increments as button is click
function ShowDesc() {
ThisText++;
switchTo(ThisText);
}
Here is the HTML code------------------------
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="score.js"></script>
</head>
<body onload="onLoad();">
<div id="main">
<div>
<center><p id="description">Read the Discription and chose your answer below.</p></center>
</div>
<br/>
<!--
<div id="Answer_Box">
<center>
<form>
<input type="checkbox" name="vehicle" value="text" id="Answer_Box_One">I have a bike
</form>
-->
<form>
<center>
<div style="float: left; width: 50%;">
<ul>
<label id="Answer_Box_One" for="male">Male</label>
<input type="radio" name="sex" id="male" value="male"><br>
<label id="Answer_Box_Two" for="male">Female</label>
<input type="radio" name="sex" id="male" value="Female"><br>
</ul>
</div>
<div style="float: right; width: 50%;">
<ul>
<label id="Answer_Box_Three" for="male">Male</label>
<input type="radio" name="sex" id="male" value="male"><br>
<label id="Answer_Box_Four" for="Not Above">Not Above</label>
<input type="radio" name="sex" id="Not Above" value="Not Above"><br>
</ul>
</div>
<button type="button" onclick="ShowDesc();">Correct</button>
</center>
</form>
</center>
</div>
</div>
</body>
</html>

Hey i am just helping because i think u r really stuck. But later please take care about what you ask and please be specific.
Your html was a bit messed so i had to change it (talking mainly about the options section cause it is the main part of your game)
now for your game let me tell you this .
<input type='radio'> should have value the same as the label that you are displaying,cause it will help you for checking for correct answer.
you have to dynamically load the options (in demo i have shown how to do it for one for rest please figure it out)
read a bit about jquery,javascript and html before you start working on this one again.
now the i have used jquery and i suggest u also use it as later on it will be of great help to you and if you know javascript then jquery would be a easy job for u.(trust me on this one).
This is the demo for your game

Related

Execute JS after a certain event

I didn't find an answer here (maybe because my knowledge in JS is very limited), so I decided to ask the question myself:
How can I execute my javascript after a certain event? I have a form and I want the JS to run after the last radio is selected but before submitting the form.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id="myform">
//various fields
</form>
<script type="text/javascript">
function myfunction() {}
</script>
</body>
</html>
I managed the function to run when loading the website and after the last field was filled/radio was checked, but i want it to run ONLY when the last radio was checked.
Thx for everyone to help me
You can use element.addEventListener(“event”, function) and element.removeEventListener(“event”, function) instead of the on attributes. It can make your code much cleaner! Here’s a simple example:
document.getElementById(“button”).addEventListener(“click”, myFunction);
function myFunction(){
alert(“hello world!”);
}
Try: onclick=“myfunction()”
For example if your code is <input type=“checkbox” onclick=“myfunction()”>
Then it might run something like this:
/* Notice how the function below corresponds with the onclick function */
function myfunction() {
alert("Box Checked!")
//Put whatever you want in here
}
function Yes() {
alert("Thanks!")
//Put whatever you want in here as well
}
function No() {
alert("Aw...")
//Put whatever you want in here as well
}
function Submit() {
alert("Thanks!")
}
<!Doctype html>
<html>
<p>Check this box!</p>
<input type="checkbox" onclick="myfunction()">Check me!</input>
<!-- notice the onclick function here -->
<br>
<br>
<p>Fill this form!</p>
<label for="username">Username: </label>
<input type="text" id="username" name="username">
<br><br>
<input onclick="Submit()"type="submit" value="Submit">
<!-- notice the onclick function here as well -->
<p>Is this answer good?</p>
<input onclick="Yes()" type="radio">
<!-- You know the drill ;) -->
<label>Yes! 😀</label>
<br>
<input onclick="No()" type="radio">
<!-- Ditto -->
<label>No! 😭</label>
</html>
This will work for most elements with a user required click (i.e Check Box, Submit button, so on...)
Just insert onclick="myfunction()".
For more information, go to this site:
https://www.w3schools.com/jsref/event_onclick.asp
Hoped this helped!
You can make a function that will do something when a certain condition is met(that is sorta an event in theory in the first place)
In other words, not every living thing that happens dispatches an event of some sort, especially composite things like that. For things like those, just wait until your logical event happens then execute some code.. the following function works like that
function onEvent(condition,whenFulfiled,eventParam){
var i=setInterval(()=>{
if(condition()){
clearInterval(i)
whenFulfiled(eventParam)
}
},0)
}
var checkboxes=document.getElementsByClassName('checkbox')
//example uses
onEvent(
function(){
return [...checkboxes]
.filter(a=>a.checked)
.length == checkboxes.length
},
function(boxes){
console.log("all boxes checked :D\nunchecking them...")
boxes.forEach(a=>a.checked=false)
},
[...checkboxes]
)
<div><h3>when checked all are checked(which is not a real event, this ad-hoc "event listener" would activate)</h3></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>

How to show all divs that contain the similar combination of classes

I would like to show specific posts on a Wordpress page and hide all others. What posts are to be shown, should depend on checkboxes checked on top of the page. A checkbox corresponds with a class. When (for example) two checkboxes are checked (two classes selected in essence), only posts containing at least those two classes in their wrapping div (besides a possible third or fourth class they may have) should be shown (and all the other posts hidden) instantly on the page.
Does anyone of you know how to pull this off?
I already managed to get the tags assigned to a post in the CMS and transfer those tags to the wrapping div of that very post as its class names, so far so good.
How to write the last piece of needed code from scratch I find very difficult to do with the small amount of knowledge I have. I understand that first the desired classes should be gathered (selected through the checked checkboxes). Then a condition should be formed (class1 AND class3 AND class7 have been selected). Then, if that condition is true for a post (‘your wrapping div contains class1, class3 and class7’), only then the post should be shown. The post could also (for example) contain class2, that’s fine, the filter though is made up of the combination of class1, class3 and class7 being present within the wrapper div, as long as that’s true, it may be shown).
I’m sure this should be a stroll through the park for a lot of you, for me it’s still pretty hard to realise from scratch, so any help you guys could give me is highly appreciated! Thanks in advance!
Thanks for your response so far, guys, closest thing I found online so far is this:
$("#filters :checkbox").click(function() {
$("div").hide();
$("#filters :checkbox:checked").each(function() {
$("." + $(this).val()).show();
});
});
It comes from this setup: http://jsfiddle.net/6wYzw/41/ > here it shows a post when its wrapping div contains classX AND/OR classY, see its working example. I reckon the part where it says
$("." + $(this).val()).show();
... needs to be adjusted, so that right here all the checked checkboxes/classes so far are taken into account using AND, not OR. Is this the only line which actually has to be adjusted in order to make my desired setup work the way I want it too?
#Lisrael > all posts should be displayed at first, then the filter starts to kick in as soon as checkboxes are starting to be clicked just like you said indeed.
Found out how to do this! With the help of an example which came close already and lot's of 'sub'examples here and there. See the code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3 align="center">Boardgamefilter</h3>
<form name="gamesettings">
<input type="checkbox" name="gamesetting" value="1p">1p<br />
<input type="checkbox" name="gamesetting" value="2p">2p<br />
<input type="checkbox" name="gamesetting" value="3p">3p<br />
<input type="checkbox" name="gamesetting" value="4p">4p<br />
<input type="checkbox" name="gamesetting" value="5p">5p<br />
<input type="checkbox" name="gamesetting" value="6plus">6plus<br />
<br />
<input type="checkbox" name="gamesetting" value="15m">15m<br />
<input type="checkbox" name="gamesetting" value="30m">30m<br />
<input type="checkbox" name="gamesetting" value="45m">45m<br />
<input type="checkbox" name="gamesetting" value="60m">60m<br />
<input type="checkbox" name="gamesetting" value="90m">90m<br />
<input type="checkbox" name="gamesetting" value="120mplus">120mplus
<br />
<br />
<input type="button" name="Un_CheckAll" value="Reset"
onClick="UnCheckAll(document.gamesettings.gamesetting)">
</form>
<br />
<br />
<div id="boardgames">
<div class="1p 2p 15m 30m" style="display: block;">1p 2p 15m 30m</div>
<div class="1p 2p 30m 45m" style="display: block;">1p 2p 30m 45m</div>
<div class="2p 30m 60m" style="display: block;">2p 30m 60m</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input[name=gamesetting]').change(function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(".")
var str = (".") + vals
$('#boardgames div').hide();
$('#boardgames div' + (str)).show();
})
function UnCheckAll(chk) {
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
$('#boardgames div').show();
}
</script>
</body>
</html>

Javascript not working for printing data one after the other

I am trying to write a JavaScript code that prints whatever is present in the body-tag again when you click on the add button. The basic idea is to add authors. For example suppose there is only 1 author then the user does not click on the add button but only selects whether he is a student or a teacher. Now suppose there are 3 authors for a particular instance then he selects whether he is a student or a teacher for author 1 and then clicks "add" button.Now the above set of questions again appears for author 2 and now user can select whether the 2nd author is student or teacher. For the 3rd author the user needs to click "add" again which appears below the 2nd author which allows user to click whether the 3rd author is student or teacher. Infact this can be carried out for n number of authors.Basically the authors should appear one after the other in sequence. I could only achive it for 1st user
<html>
<head>
<title>Authors</title>
<script>
function addauthor()
{
console.log('function is working');
var no;
but = document.getElementById("addauth");
no = Number(but.value)+1;
document.getElementById('next').innerHTML='<p><div>'+no+'</div> \
<p>Whom do you want to add ? </p> \
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label> \
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label> \
<div id=""></div> \
</p> \
<p id="next"> \
<button id="addauth" onclick="addauthor()" value="'+no+'">Add</button> \
</p>';
}
</script>
</head>
<body>
<p><div>1</div>
<p>Whom do you want to add ? </p>
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label>
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label>
<div></div>
</p>
<p id="next">
<button id="addauth" onclick="addauthor()" value="1">Add</button>
</p>
</body>
</html>
I am a newbie to JavaScript. Although the code works partially I know the code is inefficient but I am not sure of how to do it. If anyone knows a better or an efficient method or algorithm please suggest me.
This is where I am going wrong for author 3 and till author n
What's going on is that you are rewriting the #next html element instead of concatenating to it. You can concatenate to the HTML element. You also need to move the button outside of the logic you want to append to the DOM. I have put a wrapper around the elements requiring to be appended called person-container:
HTML
<div id="person-container">
<div>1</div>
<p>Whom do you want to add ? </p>
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label>
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label>
</div>
<p id="next">
<button id="addauth" onclick="addauthor()" value="1">Add</button>
</p>
JS
var no = 1;
function addauthor()
{
console.log('function is working');
but = document.getElementById("addauth");
no++;
var newEle = document.createElement('div');
newEle.classList.add = "person";
newEle.innerHTML ='<br><div>'+no+'</div> \
<p>Whom do you want to add ? </p> \
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label> \
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label> \
<div id=""></div><br>';
document.getElementById('person-container').appendChild(newEle);
}
See the fiddle: https://jsfiddle.net/gt4c6zpL/4/

Another way to show and hide buttons

The following codes works with no problem if I am running the file locally on my drive. Unfortunately, I need to upload this form to a software called MasterControl. It does not work. I was wondering if there is another way of coding that is universal to local as well as upload to a server for MasterControl.
The purpose of this code is - once you click on Yes button on the first level question then the next level questions will appear. If you click on No button on the first level and if the questions from the next level questions showing then it will clear all the selected buttons and hide the section of the second level questions.
Here is the codes:
HTML Code:
<div id="divDeathOccurred" class="fieldRow">
<div class="leftLabel labelWidth22">
<label for="">A. Has a death occurred?</label>
</div>
<div class="leftField">
<div class="formField34">
<input id="rbDeathOccurred" name="rbDeathOccurred"
type="radio" class="radiobuttonfield" title="Death Occurred"
value="Yes" onclick="javascript:USAYesNoCheckDO();" />Yes
<input id="rbDeathOccurred" name="rbDeathOccurred"
type="radio" class="radiobuttonfield" title="Death Occurred"
value="No" onclick="javascript:USAYesNoCheckDO();" />No
</div>
</div>
<p> </p>
<div id="USADOYesNo" style="display:none">
<ol type="1" class="indentList">
<li>Is there a reasonable possibility that a device failure
or malfunction was a direct or indirect factor in the death?
<br>
<input id="rbDOYesNo" name="rbDOYesNo" type="radio"
class="USDO radiobuttonfield" title="Yes Reportable" value="Yes"
onclick="javascript:USDeviceFailure30Days();" />
<label for="rbDOYesNo" class="rptColor">Yes -
reportable</label>
<input id="rbDOYesNo" name="rbDOYesNo" type="radio"
class="USDO1 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceFailure30Days();" />No - No
Report
<div id="calc" class="indentListCalc">
<input id="dt30Days3" type="text" class="textfieldCalc
labelWidth25" alt="Device Malfunction" />
</div>
<p></p>
</li>
<li>Is there a reasonable possiblity that a device design
defect was direct or indirect factor in the death?
<br>
<input id="rbDOYesNo1" name="rbDOYesNo1" type="radio"
class="USDO2 radiobuttonfield" title="Yes Reportable" value="Yes"
onclick="javascript:USDeviceDesign30Days();"/>
<label for="rbDOYesNo1" class="rptColor">Yes -
Reportable</label>
<input id="rbDOYesNo1" name="rbDOYesNo1" type="radio"
class="USDO3 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceDesign30Days();" />No - No Report
<div id="calc1" class="indentListCalc">
<input id="dt30Days1" type="text" class="textfieldCalc
labelWidth25" alt="Device Design" />
</div>
<p></p>
</li>
<li>Is there a reasonable possiblity that the device
labeling was direct or indirect factor in the death?
<br>
<input id="rbDOYesNo2" name="rbDOYesNo2" type="radio"
class="USDO4 radiobuttonfield" title="Yes Reportable"
value="Yes" onclick="javascript:USDeviceLabeling30Days();"/>
<label for="rbDOYesNo2" class="rptColor">Yes -
Reportable</label>
<input id="rbDOYesNo2" name="rbDOYesNo2" type="radio"
class="USDO5 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceLabeling30Days();"/>No - No Report
<div id="calc2" class="indentListCalc">
<input id="dt30Days2" type="text" class="textfieldCalc
labelWidth25" alt="Device Labeling" />
<p></p>
</div>
</li>
</ol>
</div>
</div> <!-- final section Death Occurred end -->
Javascript Code:
function USAYesNoCheckDO() {
if (document.getElementById('rbDeathOccurred').checked) {
document.getElementById('USADOYesNo').style.display = 'block';
} else {
document.getElementById('USADOYesNo').style.display = 'none';
document.getElementsByClassName('USDO')[0].checked = false;
document.getElementsByClassName('USDO1')[0].checked = false;
document.getElementById('calc').style.display = 'none';
document.getElementsByClassName('USDO2')[0].checked = false;
document.getElementsByClassName('USDO3')[0].checked = false;
document.getElementById('calc1').style.display = 'none';
document.getElementsByClassName('USDO4')[0].checked = false;
document.getElementsByClassName('USDO5')[0].checked = false;
document.getElementById('calc2').style.display = 'none';
}
}
I am still learning about all of this HTML, Javascript, and I am just getting into JQuery.
If you need me to put these codes in jsfiddle, please let me know.
Thank you so much,
IreneS
Update:
I forgot to add that the codes work on the server when you select the buttons and the show and hide - the one thing does not work is the clearing the selected buttons.
Thank you again.
Update 2:
After many hours of research and trying to learn Jquery, hoping that it will give me another way to get this issue resolved and get it to work on the server, unfortunately it did not. The reason I was trying Jquery, because I was looking at the other forms that were on the MasterControl server, and they were coded with Jquery. Unfortunately, being a beginner in Jquery, I am not able to get it to work on both sides - the local drive and the server. Please can someone check it and see what I am missing or doing wrong.
function getChecked(radioGroupName, index)
{
var oRadioList = document.getElementsByName(radioGroupName);
return oRadioList[index].checked;
}
function setChecked(radioGroupName, index, state)
{
var oRadioList = document.getElementsByName(radioGroupName);
oRadioList[index].checked = state;
}
function USAYesNoCheckDO()
{
if(getChecked("rbDeathOccured",0) == true)
{
$('#USADOYesNo').slideDown(1000);
}
else
{
$('#USADOYesNo').slideUp(1000);
setChecked("rbDOYesNo",0,false);
setChecked("rbDOYesNo",1,false);
setChecked("rbDOYesNo1",0,false);
setChecked("rbDOYesNo1",1,false);
setChecked("rbDOYesNo2",0,false);
setChecked("rbDOYesNo2",1,false);
}
}
Or if you have any idea how to get this issue fixed. As I mentioned before the buttons work and the show and hide of the questions work, the issue is when I want to reset and set it back to the original status - blank.
Thank you again and appreciate any help.
IreneS
Update 3:
Please anybody have any thoughts/ideas on how to fix this issue.
I really appreciate any help.
Thank you,
IreneS
Update 4:
Just incase someone have the same issue as I am and need a solution, I finally found a website after all this time of searching that gave me the answer and it works! Yeh! I just customized the coding to my needs and it works locally and on the server.
http://www.electrictoolbox.com/javascript-clear-form/
IreneS.
You use the same id attribute for multiple elements. id should be unique on the page, only name can be the same to group multiple input elements of the same type. I don't know if this is the main problem but it is a start.

Using javascript and html to show images when checkboxes are checked

I'm trying to create a page that generates simple custom reports based on the checkboxes a user clicks. On the left side I will have a vertical column of checkboxes. For simplicity's sake, lets say I have two checkboxes labeled "Population" and "Employment".
When a user is interested in seeing employment data they check the "Employment" box and the image file of the data "employment.jpg" will be displayed to the right. If they then uncheck the box, the image will disappear. If they check both boxes, both images will be similarly displayed, one below the other in the order clicked.
I'm am loosely familiar with HTML, and new to Javascript. I've been trying to do this with if statements and document.write but can't keep my checkboxes on the page when the image is generated.
Here's my current code:
<html>
<head>
<script language="javascript" type="text/javascript">
function checker(that) {
if (that.checked) {
document.write("<br /><br /><img src='employment.png'>");
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="Box" onclick="checker(this)"> Employment <br />
</form>
</body>
</html>
Here's a quick example to get you started. You can see it in action here.
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility=="visible") {
el.style.visibility="hidden";
}
else {
el.style.visibility="visible";
}
}
<label for="chkemployment">Employment</label>
<input type="checkbox" id="chkemployment" onChange="toggleVisibility('imgemployment');" /><br/>
<label for="chkpopulation">Population</label>
<input type="checkbox" id="chkpopulation" onChange="toggleVisibility('imgpopulation');" />
<hr />
<img id="imgemployment" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden"/>
<img id="imgpopulation" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden" />
This is how the solution looks like in AngularJS:
<script src="http://docs-next.angularjs.org/angular-0.10.1.min.js"
ng:autobind></script>
<p>
<input type="checkbox" name="production" id="production" />
<label for="production">Production</label>
</p>
<p>
<input type="checkbox" name="employment" id="employment" />
<label for="employment">Employment</label>
</p>
<img src="http://i.i.com.com/cnwk.1d/i/bto/20071106/OLPC_photo_540x360.jpg"
ng:show="production" />
<img src="http://www.sunriseenterprisesinc.com/main/Portals/0/EmploymentSmall.jpg"
ng:show="employment" />
You can play with the example here: http://jsfiddle.net/psyho/nrdnx/
You can handle the change event of the checkboxes. Here's a full example (without images, though): http://jsfiddle.net/minitech/hsF9s/
Usually people use a framework such as jQuery. It allows you to abstract away from the nitty gritty details and cross-browser pains. Using that, you would do the task you describe like this:
http://jsfiddle.net/3vQJZ/3/
And here's the code from that working demo:
<input type="radio" name="selectPicture" value="http://i170.photobucket.com/albums/u277/AmandaisAwesomeQUACK/monkey.gif"/>
<input type="radio" name="selectPicture" value="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" checked/>
<img id="image" src="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" alt="image selected by radio buttons"/>
$(document).ready(function(){
$('input[name=selectPicture]').click(function(){
$('#image').attr('src', $('input[name=selectPicture]:checked').val());
});
});

Categories