Javascript not working for printing data one after the other - javascript

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/

Related

Creating a simple mathematics game

I am new to the javascript developing world and I took it upon myself to create a small game that my fathers students will be able to play at school. This game consists of 4 different mathematical operations (Adding,Subtracting,Multiplication,Division). Once the student clicks on the operation button, they will then be transferred to a new page. This page will have numbers from 1 to 10. This number will be used as a static number. After the user selects this number, they will have 10 different problems to answer. The first number will be a random number from 1 to 12 and the second number will be the digit they selected on the page before. After completing the 10 problems, they will be greeted with a page that will inform them which questions they have missed. I have started the code for the addition part but I ran into several complications.
1) how do i transfer the answer from one function, to another? This will be used to check the input.
2) Will it be more intuitive to use a switch statement in order to select the operation & the static number?
3) Is there any other methods that would facilitate the making of this game?
I would like to thank you in advance and apologize for the long post. I am a bit lost and would love to get some kind of feedback.
var x;
function startAdd() {
var random = new Array();
for (var i = 0; i < 1; i++) {
random.push(Math.floor(Math.random() * 13));
// console.log(random[i]);
}
var allRadioButtons = document.getElementsByName("dif");
var secondNumber;
for (var i in allRadioButtons) {
if (allRadioButtons[i].checked) {
secondNumber = +allRadioButtons[i].value;
break;
}
}
for (var a = 0; a < 1; a++) {
document.getElementById('probFirst').innerHTML = random[a];
document.getElementById('probSecond').innerHTML = secondNumber;
/*
compareUser();
function compareUser(){
if (prob != )
} */
}
}
function myFunction() {
var x = document.getElementById("userNumb").value;
document.getElementById("Answer").innerHTML = x;
}
<title>RicoMath - Addition</title>
<body>
<h1>RicoMath</h1>
<h1 class="add">Addition</h1>
<h2>Difficulty</h2>
<div id="options">
<div>
<input id="num1" type="radio" name="dif" value="1">
<label for="num1">1</label>
</div>
<div>
<input id="num2" type="radio" name="dif" value="2">
<label for="num2">2</label>
</div>
<div>
<input id="num3" type="radio" name="dif" value="3" checked>
<label for="num3">3</label>
</div>
<div>
<input id="num4" type="radio" name="dif" value="4">
<label for="num4">4</label>
</div>
<div>
<input id="num5" type="radio" name="dif" value="5">
<label for="num5">5</label>
</div>
<button onclick="startAdd()">Begin!!!!</button>
<h4 id='probFirst'></h4>
<h4 id='probSecond'></h4>
</div>
<input type="number" id="userNumb" value="">
<button onclick='myFunction()'>Enter UserNumb</button>
<p id="Answer"></p>
</body>
1) To transfer the data to your next "page", the easy option for you would be to have seperate divs for seperate pages in the same html file. Then when you need to go the the "next page", just show the div you need to show and hide the others.
Here's a the html + pure javascript code for that with a working example:
<body>
<div id="page1" style="border-width:2px;border-style:solid">
your first page
<button onclick="showPage2()">Go to Page 2</button>
</div>
<div id="page2" style="border-width:2px;border-style:solid">
2nd page
</div>
<div id="page3">
3rd page
</div>
<script>
showPage1();
function hide(id){
document.getElementById(id).hidden = true;
}
function show(id){
document.getElementById(id).hidden = false;
}
function showPage1(){
show("page1");
hide("page2");
hide("page3");
}
function showPage2(){
show("page2");
hide("page1");
hide("page3");
}
</script>
</body>
Here's a working fiddle.
To transfer your value from the input, just use document.getElementById() since you are in the same html document.
2) To get the selected value from the radio button list, just use (as per your code):
var rates = document.getElementById('options').value;
You can use the same method to get the value from a input box. Please make sure you add a check for empty input and also to check if a radio button has been selected before getting the value.
I don't see any need to loop as you have done.
3) Definitely learn and use jquery. It will make your effort much less.
Hope this helps and happy coding!

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.

Complex selecting of specific inputs generated by for-loop

I'm trying to select some specific inputs in a list of inputs generated by a for-loop, inside some divs also generated by for-loop. That means that the selecting process is a bit messy and difficult, because the ids are dynamic.
So, here is a sample of what I have, every id is generated by a for-loop:
<div id="block0">
<input id="special0-0" class="block"></input>
<input id="special0-1" class="block"></input>
<input id="special0-2" class="block"></input>
<input id="special0-3" class="block"></input>
</div>
<div id="block1">
<input id="special1-0" class="block"></input>
<input id="special1-1" class="block"></input>
<input id="special1-2" class="block"></input>
<input id="special1-3" class="block"></input>
</div>
<div id="item0">
<input id="special0-0"></input>
<input id="special0-1"></input>
<input id="special0-2"></input>
<input id="special0-3"></input>
</div>
<div id="item1">
<input id="special1-0"></input>
<input id="special1-1"></input>
<input id="special1-2"></input>
<input id="special1-3"></input>
</div>
I want to select the inputs with id="special0-2 AND id="special1-2" BUT NOT the ones which have class="block".
I've tried several possibilities, including these two that should work to me:
var item2 = $("div[id|='item'] > input[id$='-2']");
var item2 = $("input[id|='special'][id$='-2'][class!='block']");
The problem is, for each option, console.log(item2) returns 0 and I can't apply the javascript changes I planned on them after. Thanks for your ideas :)
JSFiddle
This might be it:
$('[id^="item"]').children('[id$="-2"]:not(.block)'); // full
$('[id^="item"] > [id$="-2"]:not(.block)'); // short
First select the divs with the id's that start with 'item', in those find those with the id ending with '-2'.
I suggest you give the root items a class. If you always want the 3rd one, combined it would be:
$('.classname').children('div:nth-child(3)'); // full
$('.classname > div:nth-child(3)'); // short

Enabling multiple textareas based on radiobutton response

Here is the problem I am trying to solve:
I have a long list of questions.
Each question includes a response section, which consist of 4 radiobuttons (Yes, No, Not Seen and Not Applicable) and two textareas;
Now, textarea "observation" is disabled by default. Only user's response "No" enables this textarea.
Question: How to apply the same logic to every textarea "observation" throughout the entire set of questions.
What I have at the moment is:
A. HTML for Response buttons
<div id="Response">
<label><input type="radio" name="Radio419" value="Y" id="Radio_419Y" onchange='radioChange(this)'>Yes</label>
<label><input type="radio" name="Radio419" value="N" id="Radio_419N" onChange='radioChange(this)'>No</label>
<label><input type="radio" name="Radio419" value="NS" id="Radio_419NS" onChange='radioChange(this)'>Not Seen</label>
<label><input type="radio" name="Radio419" value="NA" id="Radio_419NA" onChange='radioChange(this)'>Not Applicable</label>
</div>
B. HTML for Textboxes
<span id="responseDetails">
<div id="Comment">
<label for="comment">Comment:</label>
<textarea name="comment" id="Comm419"</textarea></div>
<div id="Observation">
<label for="observation">Observation:</label>
<textarea name="observation" id="Obs419"</textarea></div>
</span>
C. JS for processing THIS question only
<script type="text/javascript">
document.radioChange = function (button)
{if(button.checked ) {if (button.value === "N")
{document.getElementById("Obs419").removeAttribute("disabled")}
else
{document.getElementById("Obs419").setAttribute("disabled",true)}}}
</script>
Now as it is apparent I can only apply this to question 419, referring to textbox Observation (Obs419).
How do I apply JS to cover other questions, because textareas are going to be the same throughout the questionnaire. Textarea id changes with every new question (Obs420, Obs421 etc).
Thank you in advance.
If you can pass the id into radioChange() function like this onchange='radioChange(this, '419')'
<label><input type="radio" name="Radio419" value="Y" id="Radio_419Y" onchange='radioChange(this, '419')'>Yes</label>
Then you will get that id of radio button(which would be clicked) inside radioChange() and with that dynamic id you need to just write below code.
document.radioChange = function (button, id)
{if(button.checked ) {if (button.value === "N")
{document.getElementById("Obs"+id).removeAttribute("disabled")}
else
{document.getElementById("Obs"+id).setAttribute("disabled",true)}}}
UPDATE
First of all, your both textarea tags are not closed
<textarea name="comment" id="Comm419" </textarea></div>
//-----------------------------------^
Second you will have to pass id within double quote "", like
onchange='radioChange(this, "419")'
Here is the DEMO with passing dynamic id.

Keeping score in 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

Categories