javascript project to teach kids english alphabet - javascript

ask us to write a
In this project, you are required to implement a simple web application that allows kids in
schools to learn the basic English Alphabet. The basic idea is that, the user will choose
the number of letters he wants to learn, and when clicking on each letter, another page is
opened showing an image of something that begins with that letter. In addition, some user
interaction events are collected and stored in the localStorage object of the browser to be
used in subsequent versions of the project.
The application should look something like the following:
• It has an index.html page contains a number input and a button. The user chose
how many letters (from 1 up to 26) he wants to learn, then he presses OK.
A randomly chosen letters should be selected. For example, if the user wants to
learn 3 letters, he uses the number input field and chose 3, then presses OK and
after that he will get 3 randomly chosen letters from the English alphabet.
• The next step is for the user to click on one of the letters and then an Image is
displayed showing something that begins with that letter. Images are stored in a
folder for created for each letter (You should download some images from the
internet to use them in the project).
and i am stuck at this point that when i click in the bottun generate it generate the litters but it also diplay the images !! and i cant solve it
this is the code
var div2 =document.getElementById("div2");
var div3 =document.getElementById("div3");
var generate = document.getElementById("generate");
var input = document.getElementById("input");
var letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
litterImg = [];
for (let i = 0;i < 26;i++) {
litterImg[i] = 'img\\Letter.jpg';
}
console.log(litterImg[0]);
//console.log(numberOfLitters);
var randomLetter = [];
var getRandomLetter = [] ;
var getRandomLetter1 ;
var linkImg = [];
var numberOfLitters
var randomNumber=[];
var x ;
generate.addEventListener("click",function(e){
numberOfLitters = input.valueAsNumber;
for (let index = 0; index < numberOfLitters; index++) {
randomNumber[index] = Math.floor(Math.random()*26);
}
for (let index = 0; index < numberOfLitters; index++) {
x++ ;
randomLetter[index] = document.createElement("input");
randomLetter[index].setAttribute("type","button");
randomLetter[index].setAttribute("value",letters[randomNumber[index]]);
randomLetter[index].setAttribute("id",randomNumber[index]);
randomLetter[index].setAttribute("class","Letter");
div2.appendChild(randomLetter[index]);
}
for (let index = 0; index < numberOfLitters; index++) {
randomLetter[index].onclick = addImg();
function addImg(){
linkImg[index] = document.createElement("img");
linkImg[index].setAttribute("src",litterImg[randomNumber[index]]);
div3.appendChild(linkImg[index]);}
}
});
and this is the html code
<!DOCTYPE html>
<html>
<head>
<meta>
<title>Alphabet Learner</title>
</head>
<body style="background-color: salmon;">
<div id="div" class="div">
<h1>Learn the English Litters </h1>
<label >Number of Litters: </label>
<input type="number" class="input" id="input" >
<input type="button" class="generate" id="generate" value="Generate">
<div id="div2" class="div2" style="margin-left: 123px;
margin-top: 20px;">
</div>
<div id="div3" class="div3"></div>
</div>
<script src="code.js"></script>
</body>
</html>

You can get all the input elements you created with document.querySelectorAll('.div2 input') and then loop with that to know what is the id or the value of the input clicked.
...
// create allInputs variable
var allInputs;
generate.addEventListener('click', function (e) {
numberOfLitters = input.valueAsNumber
for (let index = 0; index < numberOfLitters; index++) {
randomNumber[index] = Math.floor(Math.random() * 26)
}
for (let index = 0; index < numberOfLitters; index++) {
x++
randomLetter[index] = document.createElement('input')
randomLetter[index].setAttribute('type', 'button')
randomLetter[index].setAttribute('value', letters[randomNumber[index]])
randomLetter[index].setAttribute('id', randomNumber[index])
randomLetter[index].setAttribute('class', 'Letter')
div2.appendChild(randomLetter[index])
}
/* Here you select all the input you created */
allInputs = document.querySelectorAll('.div2 input');
console.log(allInputs);
for (let index = 0; index < allInputs.length; index++) {
allInputs[index].addEventListener('click', function(e) {
/* Here you can use the allInputs[index] to get the id or the value of your input and create your image with that index or value, check your console */
console.log(allInputs[index])
console.log(allInputs[index].value)
console.log(allInputs[index].id)
});
}
})

Related

How do I get a HTML div element to loop using javascript?

I have a block of code, a quiz creation template, and i need the block of code for the question and possible answers to be looped, for however many times the user asks for. I have been trying for hours and im really not sure whats wrong.
<div id="questionform" class="modal">
I already have the amount of questions the user would like under this line of code.
var amount = prompt("Please enter the amount of questions you would like", "<amount goes here>");
below is the javascript i am using to try and loop the writing within the div.
var i;
var amount;
var contents = document.getElementById("questionform").innerHTML;
for (i = 1; i=amount; i++) {
a.document.write(contents);
}
Your condition in your for-loop is wrong. You have an assignment instead of an evaluation.
for (i = 1; i=amount; i++)
You should be creating elements and appending them to the DOM. Avoid using document.write. Also, please begin indexing at zero, unless you need to start at 1.
Update
If you provide a name attribute to your input fields, they will be submitted with the form on submit.
input.setAttribute('name', 'answer[]');
When you hit submit, the input field values will be sent to the server as:
answer=foo&answer=bar
or:
{ "answer" : [ "foo", "bar" ] }
Refer to this if you are still confused: POST an array from an HTML form without javascript
Example
let amount = prompt("Please enter the amount of questions you would like", 5);
let questionForm = document.getElementById("question-form");
let answerList = questionForm.querySelector(".answer-list");
for (let i = 0; i < amount; i++) {
let inputWrapper = document.createElement('DIV');
let label = document.createElement('LABEL');
let input = document.createElement('INPUT');
input.setAttribute('type', 'text');
input.setAttribute('name', 'answer[]');
label.textContent = 'Answer ' + String.fromCharCode(i + 65) + ': ';
inputWrapper.classList.add('input-wrapper');
inputWrapper.appendChild(label);
inputWrapper.appendChild(input);
answerList.appendChild(inputWrapper);
}
.input-wrapper {
margin-bottom: 0.25em;
}
.input-wrapper label {
display: inline-block;
width: 5em;
font-weight: bold;
}
<form id="question-form" class="modal">
<div class="answer-list"></div>
<button type="submit">Submit</button>
</form>

Masking input value after showing a few characters

I have an form input[type=text] that I would only like to show the first few characters, followed by the corresponding number of asterisks. For instance, if the value was banana, the input would display ban*** but would still submit banana.
A password field isn't the solution because I want to show some number of characters from the actual value.
I was thinking of saving the value in a data attribute and adding/remove on keydown, updating to asterisks on blur, and changing the value on submit but worry this could get messy. I'm using jQuery so I'm open to any plugins that may be out there as well.
Here I've keep a track of original text, and inside the edit I change chars after 3 into password char.
The proper password is then stored inside a data attribute data-orig, that you can then read when you submit data.
const i = $("input");
i.on("input", function () {
const $t = $(this);
const orig = $t.attr("data-orig") || "";
const v = $t.val().split("");
for (l = 1; l < orig.length && l < v.length; l += 1) {
v[l] = orig[l];
}
$t.attr("data-orig", v.join(""));
for (l = 3; l < v.length; l += 1) {
v[l] = "●";
}
$t.val(v.join(""));
});
$("button").on("click", function () {
console.log(i.attr("data-orig"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button>Get pwd</button>
I would use a hidden input field to store the real value and add a onchange-listener to it. So when it gets an Update the visible filed will get the update to. This function have to be triggerd onLoad to
HTML
<input type="hidden" name="realField" value="banana" onChange="update()">
<input type="text" readonly="readonly">
JS
function update(){
var text = $('input[name=realField]').val();
var s = '';
for(var i=3; i<text.length; ++i){
s+='*';
}
text = text.substr(0, Math.min(text.length, 3)) + s;
$('input[name=realField] + input').val(text);
}

Updating Values in HTML output based on changing input

I currently have a set of fields and radio buttons that take in some user input. Here is an example:
<div id="age">
<input type="number" name="age1" value=60>
</div>
I am displaying all the inputted values and want the display to change when the user modifies the input. This is my attempt:
var inputElements = document.querySelectorAll('input');
for(var i = 0, len = inputElements.length ; i < len ; i++) {
inputElements[i].addEventListener('input', updateDisplay());
}
function updateDisplay () {
console.log("test");
var age = document.querySelector('input[name="age1"]').value;
document.getElementById("ageComparison").innerHTML = age;
}
I know that the program enters the method since the "test" message is printed to the console; however, I don't see any change in display according to changes in input. Would appreciate any help.
While creating the eventlistener, you're just calling updateDisplay. Remove the ().
Also, you did not put '#ageComparison' element in your code.
html:
<div id="age">
<input type="number" name="age1" value=60>
</div>
<div id="ageComparison">
</div>
js:
var inputElements = document.querySelectorAll('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].addEventListener('input', updateDisplay);
}
function updateDisplay() {
console.log("test");
var age = document.querySelector('input[name=age1]').value;
document.getElementById("ageComparison").innerHTML = age;
}
Example: https://jsfiddle.net/m6r871t6/
Try avoiding the inner double quotes
var age = document.querySelector('input[name=age1]').value;
try using
inputElements[i].addEventListener('change', updateDisplay())

5 radio buttons fill up randomly?

Hi I am trying to make five buttons as you can see and I want a function when you push "click me" it will fill up the five button randomly.
It's like a random generator for stats for a game.
I don't know if I'm doing it all wrong but I think I need some other coding for this.
Can anyone that can help me?
This is what I have:
<button onclick='myFunction()'>click me</button>
<div id="demo">
<Input type = radio Name = r1>
<Input type = radio Name = r2>
<Input type = radio Name = r3>
<Input type = radio Name = r4>
<Input type = radio Name = r5>
</div>
<script type="text/javascript">
function myFunction() {
document.getElementById('demo').innerHTML = '';
var num = 3;
var noOfButtons = Math.floor(Math.random() * num);
console.log(noOfButtons);
for (var i = 0; i < noOfButtons; i++) {
var box = document.createElement();
document.getElementById('demo');
}
}
</script>
not exactly sure what your looking for. I threw this JSFiddle together. Take a look and see if its what you're looking for.
<button id='button1'>click me</button>
<div id="demo">
<input type='radio' id='r1'>
<input type='radio' id='r2'>
<input type='radio' id='r3'>
<input type='radio' id='r4'>
<input type='radio' id='r5'>
</div>
.
var button1 = document.getElementById('button1');
button1.onclick = function () {
var noOfButtons = 5;
var pick = Math.floor(Math.random() * noOfButtons) + 1;
var radioBtn = document.getElementById('r' + pick);
radioBtn.checked = true;
}
[edit]
I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo's html to ''. I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function:
function myFunction() {
var radios = document.getElementsByClassName('myRadios');
for (var i=0; i<radios.length; i++)
{
radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
}
}
Here is a a working fiddle. Let me know if this is the functionality you were looking for or if you have any questions about how it works :)

dynamic arrays with input javascript

I am currently doing a school project where I have to use javascript to create a page where a user can key in multiple numbers from an input box.
After each number is entered there is a add button which then shows the number in another box below the input. So each number is displayed vertically down the page.
From there I need two more buttons. The first one to calculate which will add the numbers together and work out the average. The second one will clear the array to start again.
I believe I am ok with the last two buttons. What I am unsure of is how should the user input create the dynamic array which will then be displayed in the page. I have been able to get a single number input but I am missing the next step so the next number entered will dispay and allow me to build an array from which the calculations can be performed.
Please try this I think it will work for you
JAVA SCRIPT :
<script type="text/javascript">
var arr = new Array();
function addNum()
{
var temp = document.getElementById('a').value;
arr.push(temp);
document.getElementById('a').value = "";
getAvg();
}
function getAvg()
{
var sum = 0;
for(var i = 0; i < arr.length; i++){
sum += parseInt(arr[i]);
}
var avg = sum/arr.length;
document.getElementById('sum').value = sum;
document.getElementById('avg').value = avg;
}
function clearAll()
{
arr.length = 0;
document.getElementById('a').value = "";
document.getElementById('sum').value = "";
document.getElementById('avg').value = "";
}
</script>
HTML:
<table>
<tr><td><input type="text" id="a"></td>
<td>Sum :<input type="text" id="sum"></td>
<td>Avg :<input type="text" id="avg"></td></tr>
<tr><td><input type="button" value="add" onclick="addNum()"></td>
<td><input type="reset" value="reset" onclick="clearAll()"></td></tr>
</table
Easiest way would be to loop over the inputs showing the numbers and add each number that way, rather than trying to maintain an array that is updated from the first input.
Stick the displaying input elements into a container with an id, then you can do something simple like:
var container = document.getElementById("container-id"),
inputs = container.children,
total;
for (var x = 0, y = inputs.length; x < y; x++) {
total += parseInt(inputs[x].value, 10);
}
alert(total) //do something way better than alert!

Categories