javascript quiz : Display random options - javascript

I just coded a html quiz page... Here is My Javascript Code
<SCRIPT language="JavaScript" type="text/javascript">
function checkAnswer(quizForm,
theAnswer,
){
var s = "?";
var i = 0;
for(;i<quizForm.elements.length;i++)
{ if(("cc" ==
quizForm.elements[i].name) &&
(quizForm.elements[i].checked)) {
s = quizForm.elements[i].value; } }
if("?" == s)
{ document.getElementById("demo").innerHTML = "Please Click Answer";
return false; }
if(s == theAnswer)
{
document.getElementById("demo").innerHTML = "Very Good";
}
else
{
document.getElementById("demo").innerHTML = "Please Check Ur Answer";
}
return false;
}
</SCRIPT>
and my html code is
What is JavaScript?
<FORM method="POST"
onSubmit="return checkAnswer(this,'B');"
>
<INPUT TYPE="RADIO" VALUE="A" NAME="cc">
A. Another name for Java<BR>
<INPUT TYPE="RADIO" VALUE="B" NAME="cc">
B. A scripting language mostly for the web<BR>
<INPUT TYPE="RADIO" VALUE="C" NAME="cc">
C. When you use Java without compiling<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit Answer">
<p id="demo"></p>
I want to add my options (A,B,C,D) in Javascript code. which can randomly display options and also when user click right answer it shows 'Correct else Wrong

To randomize the question, you need to store your question in an array or object. Then, when you show the question, you just need to show the randomized version of the question:
let questions = [
{
questions: ["Options 1", "Option 2", "Option 3", "option 4"],
answer: "Option 2",
},
]
let randomizeArray = (arr) =>{
let Question = [],
till = arr.length;
while(Question.length != till){
if(arr.length === 1){
Question[Question.length] = arr.splice(0, 1)[0];
}else{
let random = Math.floor(Math.random()*(arr.length));
Question[Question.length] = arr.splice(random, 1)[0];
}
}
return Question;
}
Here, randomizeArray alawys return the randomize array.
You need to show user the randomized version of the question.
Then, when user selects an answer, you need to compare it with the answer. And show user the associative answer.
I think you get the idea.

Related

Assigning different values to a name in HTML checkbox input based on check status

I have an input tag as follows as part of a form submission.
<input type=“checkbox” id=“allowcheatmode” name=allowCheatMode value=“NO” onchange=“allowCheatModes()”>
And allowCheatModes in a JS function
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElementById(“allowcheatmode”).value = “YES”
} else {
document.getElementById(“allowcheatmode”).value = “NO”
}
But this is not working when I am trying to print the allowcheatmode variable after form submission. What am I doing wrong here?
1) You have included an invalid character “ and ”. You should use " in both HTML and JS.
var x = document.getElementById(“allowcheatmode”).checked
2) There is no function named getElemenetById, instead use getElementById.
3) Add if-else code in the onChange function itself. So that it can trigger when checkbox value changes
NOTE I've added an extra label to just show the current state of the checkbox. You can skip that part.
function allowCheatModes() {
var x = document.getElementById("allowcheatmode").checked
if (x) {
document.querySelector("label").textContent = "YES"
document.getElementById("allowcheatmode").value = "YES"
} else {
document.querySelector("label").textContent = "NO"
document.getElementById("allowcheatmode").value = "NO"
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
<label for="allowcheatmode">NO</label>
Shouldn't it be this:
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElemenetById(“allowcheatmode”).value = “YES”
} else {
document.getElemenetById(“allowcheatmode”).value = “NO”
}
}
Try this
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
if (isChecked) {
document.getElementById("allowcheatmode").value = "YES";
} else {
document.getElementById("allowcheatmode").value = "NO";
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
The code above will be valid, because you had typo in getElemenetById (should be getElementById, not getElemeNETById). Anyway, you will see nothing in this case, because input with type="checkbox" have no view. You can improve your code adding some div element:
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
document.getElementById("allowcheatmode-view").innerHTML = isChecked ? "YES" : "NO";
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" onchange="allowCheatModes()">
<div id="allowcheatmode-view">NO</div>
P.S.: "condition ? ifTrue : ifFalse" is ternary operator, the short form of "if"
You did two things wrong
First thing
You put if outside the function, please put if inside the function
function allowCheatModes() {
...
}
Replace with
function allowCheatModes() {
...
if(x){
...
}
}
Second thing
The function name you are using is wrong, you should use getElementById, not getElemenetById
document.getElemenetById
Replace with
document.getElementById
Below is my adjusted snippet, you can refer to it.
Have a good day :)
function allowCheatModes(){
var x = document.getElementById("allowcheatmode").checked;
if (x) {
document.getElementById("allowcheatmode").value = "YES"
} else {
document.getElementById("allowcheatmode").value = "NO"
}
console.log(document.getElementById("allowcheatmode").value);
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">

How to check if the user input exist in an Array?

Is there a way to check if an user input from text box (for example) exists in an array that I created and imported from other JS files?
And can I link all that code to an HTML button?
In Python to do this I use "in":
if a in List:
print("That's In")
PS: I know that List in Python are a little different with Arrays in JavaScript.
From my platform's JavaScript documentation:
//Use:
if (in_array('a', ['a','b',4,'z'])) {console.log('item in array.');}
//Prerequisite functions:
function in_array(s,a)
{
var r = false;
if (is_array(a))
{
for (var i = 0; i<a.length; i++)
{
if (a[i]==s) {r = true;}
}
}
else {console.log('Error: object to in_array ('+a+') is not an array.');
}
return r;
}
function is_array(a)
{
return ((a.constructor.toString().indexOf('Array') > 0) ? true : false);
}
Thanks for all, i think that i resolved my problem with array.indexOf
There's my solution below
How can i close the post ?
<!DOCTYPE html>
<form id="form" onsubmit="return false;">
<input style="position:absolute" type="text" id="userInput" /> <br>
<input style="position:absolute;" type="submit" onclick="name();" /> <br>
<script type="text/javascript">
function name() {
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var input = document.getElementById("userInput").value;
//Check if a value exists in the data1 array
if(fruits.indexOf(input) !== -1){
document.write(input, " Value exists!");
document.write(" Press F5 to reload")
} else{
document.write(input, " Value does not exists!");
document.write(" Press F5 to reload");
}
}
</script>
</form>
</html>

Text Box Search / Javascript Function Arrays **not corresponding**

I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>

Simple Age Verification in javascript

I'm a total Js noob and i'm trying to make a simple script to take values from two input tags and based on their value change a p tag. I'm probably just not using proper syntax but I can't find an answer online to how to do this.
The script is supposed to be like age verification for an r-rated movie. The first input is age and the second is whether or not the customer has an adult with them for if they are underage.
<pre>
<!DOCTYPE html>
<html>
<input type="text" id="age" value="your age">
<input type="text" id="adult" value="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
if(age.value >= 18){
oldEnough = true;
}
else{
oldEnough = false;
}
if(oldEnough == false){
if(adult.value == "y"){
result = "You are not old enough, but have an adult with you.";
}
else{
result = "You are not old enough and are unaccompanied."
}
}
else{
result = "You are old enough."
}
}
</script>
</html>
</pre>
Don't call .innerHTML on the input elements. Just set the variables to point to the elements.
When assigning the result, you need to use result.innerHTML at the time of the assignment. Assigning .innerHTML to the variable just copies the current contents of the element as a string, it doesn't make result a reference to the innerHTML property.
You should call parseInt on age, because .value is a string.
function checkAge() {
var age = document.getElementById("age");
var adult = document.getElementById("adult");
var oldEnough = false;
var result = document.getElementById("answer")
if (parseInt(age.value, 10) >= 18) {
oldEnough = true;
} else {
oldEnough = false;
}
if (oldEnough == false) {
if (adult.value == "y") {
result.innerHTML = "You are not old enough, but have an adult with you.";
} else {
result.innerHTML = "You are not old enough and are unaccompanied."
}
} else {
result.innerHTML = "You are old enough."
}
}
<input type="text" id="age" placeholder="your age">
<input type="text" id="adult" placeholder="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
The input elements can be more easily accessed if they are put in a form, and the logic can be simpler. Also, make sure you use appropriate elements and attributes, e.g. don't use value as a kind of placeholder, it should be a suitable default value (if there is one).
And don't use placeholders instead of labels, they should only be used as a hint for the kind of content required, they don't replace labels.
function checkAge(button) {
var form = button.form;
var result = document.getElementById("answer");
result.innerHTML = form.age.value >= 18? 'You are old enough.' :
form.adult.checked? 'You are not old enough, but have an adult with you.' :
'You are not old enough and are unaccompanied.';
}
<form>
<label>Age: <input type="text" name="age"></label>
<label>Adult: <input type="checkbox" name="adult"></label>
<input type="button" onclick="checkAge(this)" value="Check age">
<p id="answer"></p>
</form>

How to code radio group for alerts with Javascript

I currently have a question within my HTML and a radio group with a simple yes or no. I would like to make it so that when the user answers yes, they get an alert that says good job. and when they answer no, the alert says try again and reloads the page.
Here is the html
<div id="enterText"></div>
<img src="../img/Window1.jpg" width="500" height="300"><br>
<input type="radio" name="radio-group1" value="Yes">Yes
<input type="radio" name="radio-group1" value="No">No<br><br>
<button id="submitBtn">Submit</button>
and here is the current javascript I have
if (document.title === "Level 3"){
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked){
console.log("You clicked: "+ radioGroup[i].value);
}
}
if(radioGroup[i].value="Yes"){
alert("NICE!")
}
if(radioGroup[i].value="No"){
alert("try again!")
}
}
Try the following code for your javascript:
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked) {
if(radioGroup[i].value==="Yes"){
alert("NICE!")
}
if(radioGroup[i].value==="No"){
alert("try again!")
}
}
}
}
I modified your code, I found a couple of things wrong. Your first if statement was not returning true so I added a title. Your last two if statements, I joined them together. Those two if statements where not in your for loop. and I fixed some common Boolean and semicolons errors. Here is the finalalised result:
if (document.title === "Level 3") {
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices() {
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked) {
console.log("You clicked: " + radioGroup[i].value);
if (radioGroup[i].value === "Yes") {
alert("NICE!");
break;
} else {
alert("Try Again!");
break;
}
}
}
}
<head>
<title>Level 3</title>
</head>
<body>
<div id="enterText"></div>
<img src="../img/Window1.jpg" width="500" height="300">
<br>
<input type="radio" name="radio-group1" value="Yes">Yes
<input type="radio" name="radio-group1" value="No">No
<br>
<br>
<button id="submitBtn">Submit</button>
</body>
This code will reload the page if they say no. Also, fixed minor bugs that said that the choice was YES every time.
if (document.title === "Level 3"){
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked){
console.log("You clicked: "+ radioGroup[i].value);
if(radioGroup[i].value==="Yes"){
alert("NICE!");
}
if(radioGroup[i].value==="No"){
alert("try again!");
location.reload(); //Added this line
}
}
}
}

Categories