How to loop properly - javascript

So here is the overall of what I need to do
Start with confirming if the user wants to add a course, if they click ok it gives them a prompt to enter course if they hit cancel it finishes the program.
When the user gives an answer to the course, they then need to give their grade for that specific course.
Once those two questions are done it needs to go back to ask them if they want to add a course again
this is what i have so far
while (true) {
var entering = confirm('Do you want to enter a Course?');
if (entering = true) {
break;
}
}
var codeInput = '';
var gradeInput = '';
while (true) {
codeInput = prompt('Enter Course Code');
if (codeInput.length === 7) {
break;
}
alert('invalid code');
}
gradeInput = prompt('Enter Grade for ' + codeInput + '');
document.writeln('<table border="1">');
document.writeln('<tr>');
document.writeln('<th>Course Code</th>');
document.writeln('<th>Grade</th>');
document.writeln('<tr>');
document.writeln('<th>' +
codeInput +
'</th>');
document.writeln('<th>' +
gradeInput +
'</th>');
document.writeln('</tr>');
So I'm not sure how to loop it back to the start and how to make the program stop when you hit cancel when it asks if you want to add another course. I also do not know how to make it so if the user asks to enter another course/grade how to make them into a separate answer to add below in the table.
I hope this makes sense and if anyone can help would be lovely thank you!
ps. This has to all be done using javascript no HTML.

Working fiddle.
Wrap your code in a function so you could call it every time you enter the grad to ask it again.
I suggest to create the table and the header then append the rows when the user answers the prompts :
var number_of_rows = 0;
var table = document.createElement('table');
table.border = '1';
ask();
function ask() {
var codeInput = '';
var gradeInput = '';
var entering = confirm('Do you want to enter a Course?');
if (!entering) {
return;
} else {
while (true) {
codeInput = prompt('Enter Course Code');
if (codeInput.length === 7) {
break;
}
alert('invalid code');
}
}
gradeInput = prompt('Enter Grade for ' + codeInput + '');
if (number_of_rows === 0) {
var row = document.createElement('tr');
var th_1 = document.createElement('th');
var th_2 = document.createElement('th');
var txt_1 = document.createTextNode("Course Code");
var txt_2 = document.createTextNode("Grade");
th_1.appendChild(txt_1);
th_2.appendChild(txt_2);
row.appendChild(th_1);
row.appendChild(th_2);
table.appendChild(row);
number_of_rows++;
}
console.log(number_of_rows);
table = insertRow(codeInput, gradeInput);
document.body.appendChild(table);
number_of_rows++;
ask();
}
function insertRow(codeInput, gradeInput) {
var row = document.createElement('tr');
var td_1 = document.createElement('td');
var td_2 = document.createElement('td');
var txt_1 = document.createTextNode(codeInput);
var txt_2 = document.createTextNode(gradeInput);
td_1.appendChild(txt_1);
td_2.appendChild(txt_2);
row.appendChild(td_1);
row.appendChild(td_2);
table.appendChild(row);
return table;
}

According to here https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
If the user clicks the Cancel button, this function returns null
So all you need is to check if value is null to know if the user clicked cancel
if (codeInput == null) break

Related

How to add a difficulty to a Javascript hangman game

I want to allow the user to select the difficulty of the game. Easy is words length 3-5, Medium is length 6-9, Hard is 10-15. The word is being pulled from an AJAX API. Also, I've consulted this example but am still struggling to apply it to my own. I included extra code because I'm not sure if I could add radio buttons that store the level and word.length that then updates the word retrieved from the api to be the correct length.
var api = 'https://hangman-api.lively.software';
//add alphabet to div
alphabet.forEach((i) => {
$('.hangman-letters').append(`<div id="letter-${i}">${i}</div>`);
});
//set up initial puzzle
newPuzzle();
//set up new puzzle when user clicks "start over"
$('#game-over-replay').click(function(){
newPuzzle();
});
//trigger game on clicking letter button
$('.hangman-letters div').click(function(){
submitLetter(this.innerHTML, this);
});
//trigger game on keypress
$(window).keypress(function(e){
var thisKey = String.fromCharCode(e.which);
if(alpha.indexOf(thisKey) > -1) {
submitLetter(thisKey, document.getElementById(`letter-${thisKey}`));
}
})
//functions
//handle clicked letter or keyboard input
function submitLetter(letter, thisLetterButton) {
var isCorrect = letterChosen(letter);
if(isCorrect) $(thisLetterButton).addClass('disabled correct');
else $(thisLetterButton).addClass('disabled');
if(remainingBlanks < 1) {
gameOver(true);
}
if(totalIncorrect >= hangmanParts.length + 1) {
gameOver(false);
}
}
//wipe variables and containers and set up new game
//now called after api call is complete
function setUp(){
$('.game-over').hide();
puzzleLetterContainers = [];
previouslyChosen = '';
totalIncorrect = 0;
remainingBlanks = puzzle.length;
$('.hangman-puzzle').html('');
$('#added-parts').html('');
$('.hangman-letters div').each(function(){
this.classList = '';
})
puzzle.split('').forEach((i) => {
var thisClass = "hangman-puzzle-letters",
placeholder = " ";
if(i == ' ' || i == '-') {
thisClass += ' space';
remainingBlanks--;
placeholder = i;
}
$('.hangman-puzzle').append(`<div class="${thisClass}">${placeholder}</div>`);
});
//var difficulty[] = new difficulty;
//var difficulty[1] = Easy;
//var difficulty[2] = Medium;
//var difficulty[3] = Hard;
puzzleLetterContainers = document.getElementsByClassName('hangman-puzzle-letters');
}

Create an HTML table using Javascript Array

parse the given array (using JavaScript) and create an HTML table
Gmail - containing all email ids with domain gmail.com.
Yahoo - containing all email ids with domain yahoo.com.
Others - containing all email ids with domains not in a,b, and c, i.e., NOT gmail, hotmail and yahoo.
I want to segregate the array of emailids based on domain and show them in html table. I have tried the following code , but it doesnt work at if condition. Please help me solve this problem or alternate solution
----------
<script>
// var email ="test#gmail.com"
// var domain = email.replace(/.*#/," ");
// alert(domain);
var d1 = "gmail.com"
var d2 = "hotmail.com"
var d3 = "yahoo.com"
var email =[" test#gmail.com", "test#hotmail.com" , "test#yahoo.com"];
var i;
// var domain = email.replace(/.*#/," ");
var text = "";
for(i=0;i<email.length;i++){
var dom = email[i].replace(/.*#/," ");
if(dom[i]==d1){
// text += email[i] + "<br>";
// document.getElementById("demo").innerHTML = text;
document.write("hii hello");
}
// else if(dom == "hotmail.com"){
// // text += email[i] + "<br>";
// // document.getElementById("demo").innerHTML = text;
// document.write("hii");
// }
// else if(dom == "yahoo.com"){
// // text += email[i] + "<br>";
// // document.getElementById("demo").innerHTML = text;
// document.write("swax");
// }
else{
document.write(dom); }
}
// document.getElementById("demo").innerHTML = text;
</script>
.replace(/.*#/," ");
You should replace with an empty string
.replace(/.*#/,"");
By the way, it's not really recommended to use document.write().
To help you I wrote quickly this snippet as starting point for you (no judgement, I barely tested it):
function createTable(rows) {
const table = document.createElement('table');
for (row of rows) {
const tr = document.createElement('tr');
for (column of row) {
const td = document.createElement('td');
td.appendChild(document.createTextNode(column));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
const emails = [
'test0#gmail.com', 'test0#hotmail.com', 'test0#test.com',
'test1#gmail.com', 'test1#hotmail.com', 'test1#test.com',
];
const split = [[], [], []];
emails.forEach(email => {
switch (email.split('#')[1]) {
case 'gmail.com': split[0].push(email); break;
case 'hotmail.com': split[1].push(email); break;
default: split[2].push(email)
}
});
createTable(split);
Regards,
Vincent

JS : press enter and go to the next input

(Sorry if my english is bad)
I try to make a little game where you have to answer question in inputs. When you valid with the key "Enter", next input appear, and a new question in.
It is complicated to explain, so I leave you the test URL : nicolaslorand.com/bac.php
Here is my a part of my code :
var i = 1;
var j = 2;
$('#input'+i).keypress(function(event) {
console.log('input actuel :'+i);
console.log('input suivant :'+j);
if (event.which == 13) {
verification();
console.log("Touche entrée");
}
});
function verification(){
document.getElementById('input'+j).style.display = "block";
var index = $(".inputform").index(this) + 1;
$(".inputform").eq(index).focus();
var recup = document.getElementById('input'+i);
var verif = recup.value.toUpperCase();
var divLettre = document.getElementById('lettre');
var premiereLettre = divLettre.innerText || divLettre.textContent;
if ( verif.charAt( 0 ) === premiereLettre ) {
$("#input"+i).addClass('trueanswer');
i++; j++;
scoreTotal++;
console.log(i);console.log(j);
}
else{
$("#input"+i).addClass('falseanswer');
i++; j++;
console.log(i);console.log(j);
}
With this code, when I press enter, next input appear, but I have to write in the first input so that my answer is verified by the function.
You are using this inside function this refers to window object. i think you should use i instead of this
var index = $(".inputform").index(i) + 1;

Why does my program keep creating new elements?

This is part of the interactivity of a form.
A user can select from a range of activities. 6 of the activities are priced as 100, one of them is priced at 200.
As the user checks the boxes, a label appears, telling the user what the total price is.
Right now, the price is being calculated fine.
But every single time a box is checked, a NEW label is added. As opposed to updating the old one. Why is this happening?
This is my code:
// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
var main = document.getElementById("all");
var framework = document.getElementById("framework");
var libs = document.getElementById("libs");
var express = document.getElementById("express");
var node = document.getElementById("node");
var build = document.getElementById("build");
var npm = document.getElementById("npm");
// Calculate running total of price of events selected
var mainPrice = 200;
var otherPrice = 100;
var totalPrice = 0;
var totalLabel;
if(!totalLabel){
totalLabel = document.createElement('label');
activities.appendChild(totalLabel);
}
if(main.checked == true){
totalPrice += mainPrice;
}
if(framework.checked == true || express.checked == true) {
totalPrice += otherPrice;
}
if(libs.checked == true || node.checked == true) {
totalPrice += otherPrice;
}
if(build.checked == true) {
totalPrice += otherPrice;
}
if(npm.checked == true) {
totalPrice += otherprice;
}
var totalNumber = totalPrice.toString();
var totalText = "Total is $" + totalNumber;
totalLabel.innerHTML = totalText;
});
I assumed this would be a problem before, I thought this would fix it by only creating a new element if totalLabel didn't already exist :
if(!totalLabel){
var totalLabel = document.createElement('label');
activities.appendChild(totalLabel);
}
Any suggestions please guys?
You have a scoping problem. totalLabel, as you create it, only lives inside the function.
Put a "var totalLabel" outside the function scope and lose the "var" from the if block. So like:
var totalLabel;
document.querySelector...
You may try this:
var totalLabel;
totalLabel = document.createElement('label');
activities.appendChild(totalLabel);
document.querySelector(".activities").addEventListener("change", function(){
// code
// comment below code
//if(!totalLabel){
// totalLabel = document.createElement('label');
// activities.appendChild(totalLabel);
// }
// code
});

Not working with Edit Button in Javascript

I'm Creating an Edit button that will edit my data in my row. the problem is if I click multiple edit button it doesn't comply.
It only complies when I click 1 edit button.
HERE IS MY EXAMPLE : http://jsfiddle.net/te2wF/31/
HERES MY CODE
function editRow(t)
{
var i = t.parentNode.parentNode.rowIndex;
var table = document.getElementById('myTable');
if ( table.rows[i].cells[3].childNodes[0].value =="Edit")
{
var name = table.rows[i].cells[0].innerHTML;
var age = table.rows[i].cells[1].innerHTML;
var gender = table.rows[i].cells[2].innerHTML;
var tname = table.rows[i].cells[0];
var tage = table.rows[i].cells[1];
var tgender = table.rows[i].cells[2];
tname.innerHTML = "";
var textname = document.createElement("input");
textname.id = "textname";
tname.appendChild(textname);
tage.innerHTML = "";
var textage = document.createElement("input");
textage.id = "textage";
tage.appendChild(textage);
tgender.innerHTML = "";
var textgender = document.createElement("select");
textgender.id = "textgender";
tgender.appendChild(textgender);
document.getElementById('textname').focus();
document.getElementById("uid").innerHTML = i;
document.getElementById("textname").value = name;
document.getElementById("textage").value = age;
textgender.options.add(Option(gender));
if(gender == "Male") textgender.options.add(new Option("Female"));
else textgender.options.add(new Option("Male"));
table.rows[i].cells[3].childNodes[0].value="Save"
document.getElementById("name").disabled = true;
document.getElementById("age").disabled = true;
document.getElementById("gender").disabled = true;
document.getElementById("insert").disabled = true;
}
else
{
update(document.getElementById('uid').innerHTML);
table.rows[i].cells[3].childNodes[0].value="Edit"
document.getElementById("insert").disabled = false;
}
}
Thank you for helping.....
you should change:
textgender.options.add(Option(gender));
to
textgender.options.add(new Option(gender));
But more to the point on the edit button:
You're attempting to access the editable inputs on your table by id - but when you create a second set of textname and textage inputs, the id's are the same as the other row that you're editing. You either need to create unique id's on these elements (perhaps by appending the row number to the id), or you need to set it up so that you can only edit one row at a time (disable and grey the other rows when you're editing one)
Please, when using jsfiddle, please keep javascript on javascript tab and html on html tab to make it easier and faster to help you.
I believe you should adjust 2 places on your code:
First
document.getElementById('textname').focus();
document.getElementById("uid").innerHTML = i;
document.getElementById("textname").value = name;
document.getElementById("textage").value = age;
textgender.options.add(Option(gender));
should be
document.getElementById('textname').focus();
document.getElementById("uid").innerHTML = i;
document.getElementById("textname").value = name;
document.getElementById("textage").value = age;
textgender.options.add(new Option(gender));
Second:
else
{
update(document.getElementById('uid').innerHTML);
table.rows[i].cells[3].childNodes[0].value="Edit"
document.getElementById("insert").disabled = false;
}
should be:
else
{
update(document.getElementById('uid').innerHTML);
table.rows[i].cells[3].childNodes[0].value="Edit"
document.getElementById("name").disabled = false;
document.getElementById("age").disabled = false;
document.getElementById("gender").disabled = false;
document.getElementById("insert").disabled = false;
}
try here http://jsfiddle.net/te2wF/31/

Categories

Resources