Javascript Game for Kids - javascript

I'm trying to make a game in javascript. I still have many issues in the code. The code is supposed to have 2 buttons; one for shuffling images dice and a button to check if the kid wrote the correct answer or not.
2 buttons
1 textbox
and a place to show the answer if it's correct or not
Here is my code.
I don't know why when I put the source of document.getElementbyID("test") it shows nothing
because I want every time I click on start a random image is selected.
I would appreciate any help as I am still a beginner in javascript.
<head>
<script type="text/javascript">
function startf(){
var images = [];
index = 0;
images[0] = "<img src='1.png' length=70px width=75px>";
images[1] = "<img src='2.png' length=70px width=75px>";
images[2] = "<img src='3.png' length=70px width=75px>";
images[3] = "<img src='4.png' length=70px width=75px>";
index = Math.floor(Math.random() * images.length);
take(index);
function take(ind)
{
return document.getElementbyId("ind")="What should i put here";
}
}
function check(){
var ch=getElementbyId("answer").value;
if (ch=index+1)
{
document.getElementbyId.innerHTML="TRUE";
}
else
{
document.getElementbyId.innerHTML="False";
}
}
</script><br>
</head>
<img id="test" src="" alt="..." length="75px" width="75px" />
<body>
<input type="button" value="start" onclick="startf()">
<input id="answer" type="text" name="checkvalue" value="Enter Value" onclick="check()">
<div id="fa">
</div>
<input type="button" value=chek onclick="check()">
</body>

1- Put and end to each instructions --> ;
2- Do not use document.getElementById directly, there will be at least one occurence with an error into it and you don't want that.
function _e(id) {
return document.getElementById(id);
}
3- Always put brackets and (...) around your IF-ELSE blocks:
if (...) {
//....
} else {
//....
}
4- Every tag attributes should have " " around their values, for example:
<input type="button" value="start" onclick="check()" />
5- You could only put image paths in your array since it seems to be what needs to be updated in #test image.

It is document.getElementById check the casing. Your check function is wrong... you can't assign a value to document.getElementById function. Also your if is wrong. Do you know any JavaScript?

I'm guessing what you want is probably something like this. You seem to be trying to add or replace an element just by using document.getElementById(id) = something but that's not how it works. Instead, to change an image to another file you need to alter its src attribute. (There are other ways but this is maybe the simplest.)
// Declare the variable called number here so it can be accessed
// by all of the following functions.
var number;
// a simple function to save typing document.getElementById all the time
function _e(id) {
return document.getElementById(id);
}
function startf() {
// Pick a number between 1 and 4
number = Math.floor(Math.random() * 4 + 1);
// Set the image with id 'test' to have the source 1.png, 2.png etc.
_e('test').src = number + '.png';
}
function check() {
// note that == is used for comparison, = is used for assignment
if (_e('answer').value == number) {
_e('fa').innerHTML = "TRUE";
}
else {
_e('fa').innerHTML = "False";
}
}​

Related

Uncaught TypeError: Cannot set property 'innerHTML' of null error

I got error of Uncaught TypeError: Cannot set property 'innerHTML' of null for below script.
I added the script tags after the body. But still I get the error.
I want to show the text boxes in the same page within the div with the ID showTextBoxes.
Below is the HTML and JS.
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var a = document.writeln('<input type="text" name="Fname"><br/><br/>');
document.getElementById('showTextBoxes').innerHTML = a;
}
document.writeln('<input type="submit" name="submit">');
}
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
Actually document.write()and document.writeln() works in a different ways you think.
It actually clears all the document in your case you you are getting null.
See this
If you wanna add some element to your body you can use document.body.innerHTML += string.appendChild() can also be used but its not for stings
function showArray(){
var numofArr = parseInt(document.getElementById("numofArr").value);
for (let i = 0; i < numofArr; i++) {
var a = '<input type="text" name="Fname" /><br/><br/>'
document.getElementById('showTextBoxes').innerHTML += a;
}
document.body.innerHTML += '<input type="submit" name="submit"/>'
}
<body>
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
I think there are several ways, but I would recommend looking at append. Something like this should work:
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var textBox = document.createElement("input");
var enter = document.createElement("br");
document.getElementById('showTextBoxes').append( textBox );
document.getElementById('showTextBoxes').append( enter );
}
}
There are various places in your script which prevent it from running correctly. I'll address them step by step so you can follow along.
First of all, you should avoid inline event handlers in your HTML for the same reasons you should avoid inline style declarations. So don't use onclick=" ... " inside your HTML and instead add eventlisteners in your JS. This also gives you the ability to cancel the default behaviour or stop event propagation and such things.
Next thing is, you try to use the value of your numofArr input as upper bounds for your loop without casting it to a Number. Because <input> elements return their value as a String, this is very likely to fail. Besides, you should use the type="number" attribute instead of type="text" on that element. It's not required to do so, but just good measure.
OK, now for the showArray function:
Instead of using document.writeln (or document.write), create elements with document.createElement and add them to the DOM with appendChild.
You can see a working example below. Don't be confused by the byId and makeEl functions, they are just utilities so you don't have to write document.getElementById and document.createElement all the time.
// ====== UTILITY FUNCTIONS ======
function byId (id, root = document) {
return root.getElementById(id);
}
function makeEl (tag) {
return document.createElement(tag);
}
// ====== PROGRAM STUFF ======
function showArray (e) {
e.preventDefault();
let numofArr = parseInt(byId('numofArr').value, 10);
let output = byId('showTextBoxes');
for (let i = 0; i < numofArr; i++) {
let textIn = makeEl('input');
textIn.type = 'text';
textIn.name = 'Fname';
output.appendChild(textIn);
output.appendChild(makeEl('br'));
output.appendChild(makeEl('br'));
}
let submit2 = makeEl('input');
submit2.type = 'submit';
submit2.value = 'Submit';
document.body.appendChild(submit2);
}
byId('submit1').addEventListener('click', showArray, false);
<p>Number of arrays(array within 0-9)</p>
<input type="number" id="numofArr">
<input id="submit1" type="submit" value="Submit"><br><br>
<div id="showTextBoxes"></div>

getelementsbyname Return Undefined value

I'm a javascript newbie and I have try this.
<html>
<style>
#WoodNumInput {
width:40px;
}
</style>
<body>
<script>
var i;
var woodtypeAB = ["AB_W15_L100","AB_W20_L100", "AB_W25_L100", "AB_W30_L100"];
for (i = 0; i < 4 ; i++) {
document.write("<div id = 'box'><input type ='number' name = '" + woodtypeAB[i] + "' id = 'WoodNumInput' value = " + i + "></div><br/>");
}
</script>
<br/>
<input type = "button" value = "calculate" onclick= "Calculation()">
<div id = "Test"></div>
<script>
function Calculation() {
var ShowResult = document.getElementsByName("woodtypeAB[3]").value;
document.getElementById("Test").innerHTML = ShowResult;
}
</script>
</body>
The value returns undefined and I still can't figure it out.
Thank in advance for your help and suggestions.
This
var ShowResult = document.getElementsByName("woodtypeAB[3]").value
should be
var ShowResult = document.getElementsByName(woodtypeAB[3])[0].value
Since "woodtypeAB[3]" is surrounded by quotation marks it will be interpreted as a string rather than the actual array value.
document.getElementsByName() returns a NodeList of elements so you will have to explicitly say that you want the first item in the NodeList, hence [0]
There are a few things wrong.
First, you're trying to get the .value from a collection instead of from individual elements.
Also, the elements you're creating have a name value of AB_... but you're trying to fetch using a very different name.
I think you perhaps thought that the woodtypeAB[3] you're fetching would somehow translate to the variable and index you used to create the element's name. That's not how it works.
When you created the element, the concatenation did not add woodtypeAB[3] as the name, but rather the value located at that index of that array. So to fetch that particular name, you'd use its array value of AB_W30_L100.
<html>
<style>
#WoodNumInput {
width: 40px;
}
</style>
<body>
<input type="button" value="calculate" onclick="Calculation()">
<div id="Test"></div>
<br>
<script>
var i;
var woodtypeAB = ["AB_W15_L100", "AB_W20_L100", "AB_W25_L100", "AB_W30_L100"];
for (i = 0; i < 4; i++) {
document.write("<div id = 'box'><input type ='number' name = '" + woodtypeAB[i] + "' id = 'WoodNumInput' value = " + i + "></div><br/>");
}
</script>
<br/>
<script>
function Calculation() {
var ShowResult = document.getElementsByName("AB_W30_L100");
if (ShowResult.length != 0) {
document.getElementById("Test").innerHTML = ShowResult[0].value;
}
}
</script>
</body>
Although something tells me that you actually are going to want to select all those input elements and perform some calculation on them. That'll require additional tweaks to your code.

Preserve value of the text field with javascript

I build a little snippet with javascript to add more fields by clicking a button. It works fine and add the field as it should but it discards the values of the already existing fields on clicking the add more button.
You can run the snippet below to check the issue ... Please add 2-3 fields and type something in those fields and then add another field. You'll see what is happening.
var fldsContainer = document.getElementById('fields');
var fld = '<p><input name="test[]" type="text"></p>';
function addField() {
fldsContainer.innerHTML += fld;
}
<div id="fields"></div>
<button onclick="addField()">Add More Field</button>
I know in jQuery we can simply .append() but I need a solution in javascript. Is there append method in javascript?
Or any other method to resolve my issue would be appreciated :)
It is because the content of fldsContainer is rerendered every time with a brand new list of fields. You need to append to the container. Try something like the insertAdjacentHTML() method.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
var fldsContainer = document.getElementById('fields');
var fld = '<p><input name="test[]" type="text"></p>';
function addField() {
fldsContainer.insertAdjacentHTML('beforeend', fld);
}
<div id="fields"></div>
<button onclick="addField()">Add More Field</button>
It may seem larger and maybe overkill but i prefer tracking all my inputs into an array so that i separate myself from needing to possibly query DOM elements in future.
var fldsContainer = document.getElementById('fields');
var fields = [];
function render() {
fldsContainer.innerHTML = getFields();
}
function addField() {
fields.push(fields.length ? getField(fields.length) : getField(0));
render();
}
function setValue(input, i) {
fields[i].value = input.value;
}
function getFields() {
var str = ''
fields.forEach(function(field) {
str += (`<p><input name="${field.name}" value="${field.value}" type="text" onchange="setValue(this, ${field.index})"></p>`);
});
return str;
}
function getField(index) {
return {
index,
name: `test${index}`,
value: ''
}
}
<div id="fields"></div>
<button onclick="addField()">Add More Field</button>

How to add +1 to a text value every click i do?

I want to add +1 to a text value but when I click it doesn't add anything...
I think is a updating time but i am not sure...
<input type="text" id="cliccare" value="0">
<img src="http://www.sinalphoto.com/wp-content/uploads/2012/08/no-copyright.png" class="click" onclick="clicca()"/>
punticlick = 1;
punti = document.getElementById("cliccare").value ;
function clicca() {
punti += punticlick;
}
I don't really know if it is correct the onclick on the img...
You cannot add punticlick to punti, it makes no sense: in javascript, punti += punticlick equals to punti = punti + punticlick. Instead, you have to do this:
punticlick = 0;
punti = document.getElementById("cliccare");
function clicca(){
punticlick++;
punti.value = punticlick;
}
Check the fiddle: https://jsfiddle.net/jn9dqfp4/1/
punti = document.getElementById("cliccare").value is outside the function clicca. So on every click it wont get new value
Secondly since you will add one you can directly add with punti. I dont see any use of second variable
Thirdly once you have updated the value of punti you need to update value of the DOM
function clicca(){
punti = parseInt(document.getElementById("cliccare").value,10) ; // Convert to integer
punti += 1;
document.getElementById("cliccare").value=punti
}
JSFIDDLE
A very shortcut (mostly discouraged) way is like this
cliccare.onclick = e => ++e.target.value
<input type="text" id="cliccare" value="0">
you can just set onclick attribute:
onclick="document.getElementById('cliccare').value++"
<input type="text" id="cliccare" value="0">
<img src="http://www.sinalphoto.com/wp-content/uploads/2012/08/no-copyright.png" class="click" onclick="clicca()"/>
<script>
var pun = 1;
punti = document.getElementById("cliccare").value ;
function clicca(){
punti=pun;
document.getElementById("cliccare").value=punti;
pun++;
}
</script>
Try This
You can use onclick attribute for almost any html tag, but the code snippet you've wrote won't work, because after the increment of the value you need to set that value back into input tag, so your java script part would look like this:
<script>
punticlick = 1;
function clicca() {
punti = document.getElementById("cliccare").value;
punti += punticlick;
document.getElementById("cliccare").value = punti;
}
</script>

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Categories

Resources