Javascript click and open new div - javascript

what I'm trying to do for a long time is that; how can I open or create a new window using js button click. Example, I'm going to provide my simple quiz app code. I want to add a new button named "Start". If anyone click the button "Start", the quiz will be start. And the "Start" button will remove.
I've added a simple button for this purpose, but not removing the button after click "Start" button. How can I do it ?
My code example:
$("#start-quiz").click(function(){
const
rand = n => Math.floor(Math.random() * n),
swap = (t, i, j) => { let q = t[i]; t[i] = t[j]; t[j] = q; return t; },
shuffle = (arr = []) => {
let copy = arr.slice(0, 2), last = copy.length, n;
while (last > 0) { n = rand(last); swap(copy, n, --last); }
return copy;
};
var total_seconds = 1220 * 1;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);
var timer;
function CheckTime() {
document.getElementById("quiz-time-left1").innerHTML = '<i class="fa fa-clock-o"></i> ' + c_minutes + 'm' + ':' + c_seconds + 's';
if (total_seconds <= 0) {
score();
} else {
total_seconds = total_seconds - 1;
c_minutes = parseInt(total_seconds / 60);
c_seconds = parseInt(total_seconds % 60);
timer = setTimeout(CheckTime, 1000);
}
}
timer = setTimeout(CheckTime, 1000);
const quizData = [{
question: "Which language runs in a web browser?",
a: "Java",
b: "C",
c: "Python",
d: "JavaScript",
correct: "d",
}, {
question: "What does CSS stand for?",
a: "Central Style Sheets",
b: "Cascading Style Sheets",
c: "Cascading Simple Sheets",
d: "Cars SUVs Sailboats",
correct: "b",
}, {
question: "What does HTML stand for?",
a: "Hypertext Markup Language",
b: "Hypertext Markdown Language",
c: "Hyperloop Machine Language",
d: "Helicopters Terminals Motorboats Lamborginis",
correct: "a",
}, {
question: "What year was JavaScript launched?",
a: "1996",
b: "1995",
c: "1994",
d: "none of the above",
correct: "b",
}, ];
const quiz = document.getElementById("quiz");
const answerElements = document.querySelectorAll(".answer");
const questionElement = document.getElementById("question");
const a_text = document.getElementById("a_text");
const b_text = document.getElementById("b_text");
const c_text = document.getElementById("c_text");
const d_text = document.getElementById("d_text");
const submitButton = document.getElementById("submit");
const randomizedQuestions = shuffle(quizData).slice(0, 10);
let currentQuestion = 0;
let score = 0;
const deselectAnswers = () => {
answerElements.forEach((answer) => (answer.checked = false));
};
const getSelected = () => {
let answer;
answerElements.forEach((answerElement) => {
if (answerElement.checked) answer = answerElement.id;
});
return answer;
};
const loadQuestion = () => {
deselectAnswers();
const currentQuestionData = randomizedQuestions[currentQuestion];
questionElement.innerText = currentQuestionData.question;
a_text.innerText = currentQuestionData.a;
b_text.innerText = currentQuestionData.b;
c_text.innerText = currentQuestionData.c;
d_text.innerText = currentQuestionData.d;
};
loadQuestion();
submitButton.addEventListener("click", () => {
const answer = getSelected();
if (answer) {
if (answer === randomizedQuestions[currentQuestion].correct) score++;
currentQuestion++;
let asd = randomizedQuestions.length - score;
let ssrate = (1220 - Math.floor(total_seconds));
let ggg = "";
if (ssrate < 12) ggg = "good morning";
else if (ssrate < 16) ggg = "ghfgdfgh ning";
else if (ssrate < 24) ggg = "asaasasasa ng";
let avg = Math.round(score * 100 / randomizedQuestions.length);
document.getElementById("myProgress").value = avg;
if (currentQuestion < randomizedQuestions.length) loadQuestion();
else {
// stop timer
clearInterval(timer);
quiz.innerHTML = "<h2>Total Question : " + quizData.length + "<br>" + "Correct Ans : " + score + " <br> Wrong Ans : " + asd + " <br> Average : " + avg + " % <br> Time Usage : " + ssrate + " Seconds <br> Average : " + ggg + " % <br><br> <br><br> <button class='mi-ripple mi-ripple-light' onclick='location.reload()'>Play Again</button></h2>"
}
}
});
});
* {
box-sizing: border-box;
}
body {
background-color: #b8c6db;
background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 100%);
font-family: "Poppins", sans-serif;
margin: 0;
}
.quiz-container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px 2px rgba(100, 100, 100, 0.1);
width: 600px;
max-width: 95vw;
overflow: hidden;
}
.quiz-header {
padding: 4rem;
}
h2 {
padding: 1rem;
text-align: center;
margin: 0;
}
ul {
list-style-type: none;
padding: 0;
}
ul li {
font-size: 1.2rem;
margin: 1rem 0;
}
ul li label {
cursor: pointer;
}
button {
background-color: #8e44ad;
color: #fff;
border: none;
display: block;
width: 100%;
font-size: 1.1rem;
font-family: inherit;
padding: 1.3rem;
}
button:hover {
background-color: #732d91;
}
button:focus {
outline: none;
background-color: #5e3370;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<button id="start-quiz"> Start </button>
<div class="quiz-container" id="quiz">
<div class="quiz-header">
<h2 id="question">Question is loading...</h2>
<div class="mi-center" id="quiz-time-left1" ></div>
<ul>
<li> <input type="radio" name="answer" id="a" class="answer" /> <label for="a" id="a_text">Answer...</label> </li>
<li> <input type="radio" name="answer" id="b" class="answer" /> <label for="b" id="b_text">Answer...</label> </li>
<li> <input type="radio" name="answer" id="c" class="answer" /> <label for="c" id="c_text">Answer...</label> </li>
<li> <input type="radio" name="answer" id="d" class="answer" /> <label for="d" id="d_text">Answer...</label> </li>
</ul>
</div> <button id="submit" class="mi-ripple mi-ripple-light" >Submit</button>
</div>
<progress id='myProgress' value='' max='100'>
To sum up, I want like that image: . When anyone will click on start button, the quiz will start. Like that:

$("#start-quiz").click(function(){
// add class to quiz-container to show quiz container
$("#quiz").addClass("active");
// add class to start-quiz to hide start button
$("#start-quiz").addClass("active");
const
rand = n => Math.floor(Math.random() * n),
swap = (t, i, j) => { let q = t[i]; t[i] = t[j]; t[j] = q; return t; },
shuffle = (arr = []) => {
let copy = arr.slice(0, 2), last = copy.length, n;
while (last > 0) { n = rand(last); swap(copy, n, --last); }
return copy;
};
var total_seconds = 1220 * 1;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);
var timer;
function CheckTime() {
document.getElementById("quiz-time-left1").innerHTML = '<i class="fa fa-clock-o"></i> ' + c_minutes + 'm' + ':' + c_seconds + 's';
if (total_seconds <= 0) {
score();
} else {
total_seconds = total_seconds - 1;
c_minutes = parseInt(total_seconds / 60);
c_seconds = parseInt(total_seconds % 60);
timer = setTimeout(CheckTime, 1000);
}
}
timer = setTimeout(CheckTime, 1000);
const quizData = [{
question: "Which language runs in a web browser?",
a: "Java",
b: "C",
c: "Python",
d: "JavaScript",
correct: "d",
}, {
question: "What does CSS stand for?",
a: "Central Style Sheets",
b: "Cascading Style Sheets",
c: "Cascading Simple Sheets",
d: "Cars SUVs Sailboats",
correct: "b",
}, {
question: "What does HTML stand for?",
a: "Hypertext Markup Language",
b: "Hypertext Markdown Language",
c: "Hyperloop Machine Language",
d: "Helicopters Terminals Motorboats Lamborginis",
correct: "a",
}, {
question: "What year was JavaScript launched?",
a: "1996",
b: "1995",
c: "1994",
d: "none of the above",
correct: "b",
}, ];
const quiz = document.getElementById("quiz");
const answerElements = document.querySelectorAll(".answer");
const questionElement = document.getElementById("question");
const a_text = document.getElementById("a_text");
const b_text = document.getElementById("b_text");
const c_text = document.getElementById("c_text");
const d_text = document.getElementById("d_text");
const submitButton = document.getElementById("submit");
const randomizedQuestions = shuffle(quizData).slice(0, 10);
let currentQuestion = 0;
let score = 0;
const deselectAnswers = () => {
answerElements.forEach((answer) => (answer.checked = false));
};
const getSelected = () => {
let answer;
answerElements.forEach((answerElement) => {
if (answerElement.checked) answer = answerElement.id;
});
return answer;
};
const loadQuestion = () => {
deselectAnswers();
const currentQuestionData = randomizedQuestions[currentQuestion];
questionElement.innerText = currentQuestionData.question;
a_text.innerText = currentQuestionData.a;
b_text.innerText = currentQuestionData.b;
c_text.innerText = currentQuestionData.c;
d_text.innerText = currentQuestionData.d;
};
loadQuestion();
submitButton.addEventListener("click", () => {
$("#myProgress").addClass("active");
const answer = getSelected();
if (answer) {
if (answer === randomizedQuestions[currentQuestion].correct) score++;
currentQuestion++;
let asd = randomizedQuestions.length - score;
let ssrate = (1220 - Math.floor(total_seconds));
let ggg = "";
if (ssrate < 12) ggg = "good morning";
else if (ssrate < 16) ggg = "ghfgdfgh ning";
else if (ssrate < 24) ggg = "asaasasasa ng";
let avg = Math.round(score * 100 / randomizedQuestions.length);
if (currentQuestion < randomizedQuestions.length) loadQuestion();
else {
// stop timer
clearInterval(timer);
quiz.innerHTML = "<h2>Total Question : " + quizData.length + "<br>" + "Correct Ans : " + score + " <br> Wrong Ans : " + asd + " <br> Average : " + avg + " % <br> Time Usage : " + ssrate + " Seconds <br> Average : " + ggg + " % <br><br> <br><br> <button class='mi-ripple mi-ripple-light' onclick='location.reload()'>Play Again</button></h2><progress id='myProgress' value='"+avg+"' max='100'>"
}
}
});
});
* {
box-sizing: border-box;
}
body {
background-color: #b8c6db;
background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 100%);
font-family: "Poppins", sans-serif;
margin: 0;
}
.quiz-container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px 2px rgba(100, 100, 100, 0.1);
width: 600px;
max-width: 95vw;
overflow: hidden;
display:none;
}
.quiz-container.active{
display:block;
}
.quiz-header {
padding: 4rem;
}
h2 {
padding: 1rem;
text-align: center;
margin: 0;
}
ul {
list-style-type: none;
padding: 0;
}
ul li {
font-size: 1.2rem;
margin: 1rem 0;
}
ul li label {
cursor: pointer;
}
button {
background-color: #8e44ad;
color: #fff;
border: none;
display: block;
width: 100%;
font-size: 1.1rem;
font-family: inherit;
padding: 1.3rem;
}
button:hover {
background-color: #732d91;
}
button:focus {
outline: none;
background-color: #5e3370;
}
#start-quiz.active{
display:none;
}
#myProgress{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<button id="start-quiz"> Start </button>
<div class="quiz-container" id="quiz">
<div class="quiz-header">
<h2 id="question">Question is loading...</h2>
<div class="mi-center" id="quiz-time-left1" ></div>
<ul>
<li> <input type="radio" name="answer" id="a" class="answer" /> <label for="a" id="a_text">Answer...</label> </li>
<li> <input type="radio" name="answer" id="b" class="answer" /> <label for="b" id="b_text">Answer...</label> </li>
<li> <input type="radio" name="answer" id="c" class="answer" /> <label for="c" id="c_text">Answer...</label> </li>
<li> <input type="radio" name="answer" id="d" class="answer" /> <label for="d" id="d_text">Answer...</label> </li>
</ul>
</div> <button id="submit" class="mi-ripple mi-ripple-light" >Submit</button>
</div>

$("#start-quiz").click(function(){
const thisElement = document.getElementById("start-quiz")
thisElement.remove()
.......
}

Related

Generate a txt report through JavaScript and HTML

I have written HTML \ JavaScript code. The HTML page getting the three details from the end user. Based on the input from the user i want that javascript generate the barcode numbers and download the report as txt file. Here variable "B12" is a Barcode number.
Code is shown here :
const AL = document.getElementById("N1").value;
var to = Number(document.getElementById("N3").value);
var i = 1
var barcode = "1" + document.getElementById("N2").value;
while (i < to) {
const myArray = barcode.split("");
let B1 = myArray[1] * 8
let B2 = myArray[2] * 6
let B3 = myArray[3] * 4
let B4 = myArray[4] * 2
let B5 = myArray[5] * 3
let B6 = myArray[6] * 5
let B7 = myArray[7] * 9
let B8 = myArray[8] * 7
let B9 = B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8
let B10 = B9 % 11
let B11 = 11 - B10
B11 = B11 === 10 ? '0' : B11;
B11 = B11 === 11 ? '5' : B11;
rem = barcode.substring(1);
let B12 = AL + rem + B11 + "IN"
i++;
barcode++;
}
<form id="my-form">
<label for="T1">BARCODE FIRST TWO CHARATER</label><br><br>
<input type="" text " maxlength="2 " onkeyup="this.value=t his.value.toUpperCase(); " id="N1 " onchange="validity.valid||(value='' ) " required> <br><br>
<label for="T2 ">Barode Starting Eight Numbers:</label><br><br>
<input type="text " pattern="[0-9]{8} " maxlength="8 " onchange="validity.valid||(value='' ) " id="N2 " required ><br><br>
<label for="T3 ">Number of Barcode (Max 1000):</label><br><br>
<input type="number " id="N3 " min="1 " max="1000 " onchange="validity.valid||(value='' ) " required ><br><br>
<center><button type="submit " name="myButton ">Submit</button></center>
</form>
I want that javascript loop generate the report with the variable value "B12" and download as a text file while user click on submit button. Please help in the matter.
Maybe you can try that...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Barcode Number Generaot</title>
<style>
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 18px;
}
legend { font-weight: bold; padding: 0 .8em; }
fieldset { margin: 1em; width: 15em; }
label, input, button, pre { display: block; float: left; clear: both; margin-top: 0.2em; }
label { margin-top: 0.7em; font-size: .9em;}
input { text-align: center; }
button { margin-top: 2em; width: 6em; }
fieldset button:last-of-type { clear: none; float: right; }
pre { font-family: 'Courier New', Courier, monospace; font-size: 12px; margin: .8em;}
</style>
</head>
<body>
<form id="my-form" action="#">
<fieldset>
<legend>BarCode</legend>
<label>1st TWO characters</label>
<input name="N1" type="text" autocomplete="off" pattern="[A-Za-z0-9]{2}" required >
<label>1st Eight digits:</label>
<input name="N2" type="number" min="1" max="99999998" required >
<label>Number of Barcode (Max 1000):</label>
<input name="N3" type="number" min="1" max="10000" required value="1">
<button type="reset">clear</button>
<button type="submit">generate</button>
</fieldset>
</form>
<label>Generated BarCodes:</label>
<pre id="BC-genered"></pre>
<script>
const
CRcode = `\n` // carriage return
, writeToTextFile = (text, fileName) =>
{
let textFile = null;
const makeTextFile = (text) =>
{
const data = new Blob([text], { type: 'text/plain' });
if (textFile !== null)
{
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
let link = document.createElement('a');
link.setAttribute('download', fileName);
link.href = makeTextFile(text);
link.click();
}
, BCgen = document.querySelector('#BC-genered')
, myForm = document.querySelector('#my-form')
, digtsM = [8,6,4,2,3,5,9,7]
;
myForm.N1.oninput = () =>
{
myForm.N1.value = myForm.N1.value.toUpperCase();
if (myForm.N1.value.length > 2)
myForm.N1.value = myForm.N1.value[0] + myForm.N1.value[2];
}
myForm.N3.oninput = () =>
{
let N2_max = 99999999 - myForm.N3.valueAsNumber;
if ( myForm.N2.valueAsNumber > N2_max)
myForm.N2.valueAsNumber = N2_max;
myForm.N2.max = N2_max;
}
myForm.onreset = () =>
{
BCgen.textContent = '';
}
myForm.onsubmit = e =>
{
e.preventDefault() // disable submit (no page reloading in this case)
BCgen.textContent = '';
let B_1_8_CodeN = myForm.N2.valueAsNumber;
for (let i=myForm.N3.valueAsNumber; i--;)
{
let
Bcode = B_1_8_CodeN.toString(10).padStart(8, '0')
, B11 = 11 - ([...Bcode].map((x,i)=> x *digtsM[i]).reduce((sum,v)=>sum+v) % 11)
;
B11 = (B11 === 10) ? 0 : ( B11 === 11) ? 5 : B11;
BCgen.textContent += myForm.N1.value
+ Bcode
+ B11
+ 'IN'
+ CRcode;
B_1_8_CodeN++;
}
writeToTextFile(BCgen.textContent, `${myForm.N3.value}_Barcodes_${myForm.N1.value}_${myForm.N2.value}.txt`);
}
</script>
</body>
</html>

JavaScript/HTML Word Guessing Game: difficulty levels w/drop-down

I am working on a project to have a random word guessing game. So far most of the code is working but I am trying to implement some rules on the length of words displayed to the user as a measure of game difficulty (shorter words = easier, etc). I am using a drop-down menu to get the user's setting selection, and then have rules in the JS tags that are supposed to be handling this.
After toying around with this for several days, I was hoping that a fresh pair of eyes might have a suggestion about where I am going wrong to be able to enforce the rules I am trying to enforce?
The specific functions that should be handling this are setDifficulty(), getSelection(), and randomWord()
<html lang="en">
<head>
<style>
body {
background-color: rgb(231, 223, 223);
align-content: center;
margin: 2px;
padding: auto;
}
h1 {
text-align: center;
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: rgb(187, 212, 235);
margin: auto;
}
h4 {
text-align: center;
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: auto;
}
div {
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: rgb(231, 223, 223);
}
button {
background-color: rgba(65, 127, 207, 0.781);
color: rgb(255, 255, 255);
padding: 1%;
margin-bottom: 2%;
flex-wrap: wrap;
font-size: xx-large;
border: 3px;
border-radius: 5px;
}
button:disabled {
background-color: rgba(65, 127, 207, 0.363);
}
label {
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: 3px;
border-radius: 5px;
}
</style>
<meta charset="UTF-8">
<title>Word Guessing Game</title>
</head>
<body>
<label for="difficulty">Choose difficulty level:</label>
<select name="difficulty" id="difficulty_setting">
<option value="Easy" onclick="setDifficulty()">Easy</option>
<option value="Medium" onclick="setDifficulty()">Medium</option>
<option value="Hard" onclick="setDifficulty()">Hard</option>
</select>
<div class="container">
<h1 class="text-center">Random Word Guessing Game</h1>
<div class="float-right" style="position: absolute; text-align: left;">Wrong Guesses: <span id='mistakes'>0</span> of <span id='maxWrong'></span></div>
<div class="text-center">
<h3>Guess the word:</h3>
<p style="font-size: 56px;" id="wordSpotlight">The word to be guessed goes here</p>
</div>
<div id="keyboard"></div>
<button class="btn btn-info" onClick="restart()">Restart</button>
</div>
<script type="text/javascript">
let random_words = [
"plankton",
"pitman",
"dexamethasone",
"marabout",
"wintertime",
"trencherman",
"subtilize",
"cursorial",
"asterism",
"jam",
"bacteriostat",
"unworn",
"nonuniformity",
"subpart",
"groats",
"quintette",
"blowtube",
"ethnographical",
"bulbous",
"cataphoretic",
"difficult",
"opacify",
"credence",
"sextette",
"mot",
"prosthodontics",
"whippletree",
"life",
"cook",
"toxic",
"quadrature",
"tawdrily",
"escalader",
"clincher",
"ataxia",
"chiton",
"pains",
"straining",
"tenderize",
"circadian",
"wreak",
"foam",
"artemisia",
"pietistic",
"commemoration",
"excise",
"phalanger",
"decidua",
"cinematography",
"supportable",
"unspoilt",
"hermeneutics",
"whipsaw",
"quartan",
"transportable",
"imbrue",
"oxtongue",
"flogging",
"intramolecular",
"mechanism",
"busted",
"talker",
"sedum",
"glial",
"youthful",
"deviationist",
"headpin",
"realise",
"hygiene",
"worst",
"isosmotic",
"narcoleptic",
"confidently",
"boneset",
"tugboat",
"bimanual",
"daredeviltry",
"bris",
"trip",
"notably",
"repartee",
"suckling",
"hymnody",
"pleating",
"graffiti",
"assuredly",
"moment",
"isotropic",
"absconder",
"microspore",
"adobe",
"photoconductivity",
"stray",
"stalk",
"squelch",
"animistic",
"pretentiousness",
"unsmoothed",
"goalmouth",
"exclusiveness",
"bullpen",
"unasked",
"dilettantish",
"dedication",
"happily",
"squealer",
"perineurium",
"whatchamacallit",
"appreciativeness",
"topographically",
"conjuncture",
"resurvey",
"vaned",
"homo",
"upcurved",
"houseful",
"microdot",
"hated",
"literature",
"hydrophilic",
"collie",
"phycoerythrin",
"canine",
"unmanful",
"scrim",
"wanted",
"enantiomorphism",
"theologian",
"gastronomical",
"bura",
"malocclusion",
"superincumbent",
"circumferential",
"interrelated",
"calamine",
"subsidizer",
"sarcoplasm",
"eagerly",
"incautiously",
"priorship",
"gooseneck",
"wearisome",
"preciously",
"lust",
"liger",
"ovary",
"garganey",
"slather",
"hisser",
"counterfoil",
"divisible",
"hypochondria",
"statute",
"education",
"byword",
"damp",
"hornbeam",
"levity",
"nucha",
"fauteuil",
"rho",
"soothsaying",
"decreased",
"faze",
"lamia",
"above",
"artful",
"schmuck",
"stocked",
"carabiner",
"incomparably",
"unfaithfully",
"parturient",
"erotism",
"menu",
"pall",
"technical",
"stile",
"expulsion",
"spitball",
"doubting",
"wheelchair",
"aptly",
"aedes",
"successfulness",
"abductor",
"offerer",
"bloody",
"tenderheartedness",
"amusive",
"streptococci",
"gnaw",
"curiousness",
"hemorrhage",
"theologise",
"uninhabited",
"strep",
"unadoptable",
"prophetic",
"somite",
"pythoness",
"governable",
"churlish",
"craniate",
"confusion",
"smilingly",
"accruement",
"oftener",
"coho",
"scripture",
"unprovoked",
"adenohypophysis",
"fitter",
"pronouncement",
"replacing",
"custodial",
"dynamiter",
"vespers",
"hostility",
"knoll",
"vendor",
"sprig",
"stave",
"raphia",
"canfield",
"paint",
"data",
"teleconference",
"tractability",
"knit",
"amazement",
"airfield",
"cesium",
"galactic",
"axial",
"buffalo",
"unsaddled",
"pygmy",
"brewer",
"hazel",
"inauthentic",
"herrenvolk",
"uncommercialized",
"exasperatingly",
"irony",
"solan",
"subsequence",
"outclass",
"etch",
"regalia",
"unanswered",
"prospective",
"rumormonger",
"forecastle",
"mineralogy",
"adorability",
"photogravure",
"pronucleus",
"underpopulated",
"disgrace",
"smutch",
"ohmage",
"cabomba",
"emptying",
"wordsmith",
"charitable",
"sadomasochism",
"web",
"railroader",
"allow",
"pennon",
"preservation",
"mollah",
"prematurity",
"puzzlement",
"megaloblast",
"adulterating",
"dowager",
"shirtfront",
"exchequer",
"transplanter",
"turntable",
"heedlessness",
"escapist",
"calf",
"aortic",
"rumored",
"sagamore",
"form",
"settle",
"persuasiveness",
"ineptitude",
"trembles",
"navigator",
"gabbro",
"disappear",
"thermocouple",
"spay",
"frisking",
"haft"
]
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
function handleGuess(chosenLetter) {
guessed.indexOf(chosenLetter) === -1 ? guessed.push(chosenLetter) : null;
document.getElementById(chosenLetter).setAttribute('disabled', true);
if (answer.indexOf(chosenLetter) >= 0) {
guessedWord();
checkIfGameWon();
} else if (answer.indexOf(chosenLetter) === -1) {
mistakes++;
updateMistakes();
checkIfGameLost();
updateHangmanPicture();
}
}
function checkIfGameWon() {
if (wordStatus === answer) {
document.getElementById('keyboard').innerHTML = 'You Won!!!';
}
}
function checkIfGameLost() {
if (mistakes === maxWrong) {
document.getElementById('wordSpotlight').innerHTML = 'The answer was: ' + answer;
document.getElementById('keyboard').innerHTML = 'You Lost!!!';
}
}
function guessedWord() {
wordStatus = answer.split('').map(letter => (guessed.indexOf(letter) >= 0 ? letter : " _ ")).join('');
document.getElementById('wordSpotlight').innerHTML = wordStatus;
}
function updateMistakes() {
document.getElementById('mistakes').innerHTML = mistakes;
}
function generateButtons() {
let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
`
<button
class="btn btn-lg btn-primary m-2"
id='` + letter + `'
onClick="handleGuess('` + letter + `')"
>
` + letter + `
</button>
`).join('');
document.getElementById('keyboard').innerHTML = buttonsHTML;
}
function restart() {
mistakes = 0;
guessed = [];
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
function setDifficulty() {
mistakes = 0;
guessed = [];
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
document.getElementById('maxWrong').innerHTML = maxWrong;
var diff_setting = document.getElementById('difficulty_setting');
randomWord();
generateButtons();
guessedWord();
function getSelection(){
// select difficulty
//var selection = diff_setting;
let easy_game = random_words.filter((easy_words) => {
if(easy_words.length < 6){
return easy_words;}});
let medium_game = random_words.filter((med_words) => {
if(med_words.length <= 9){
return med_words;}});
let hard_game = random_words.filter((hard_words) => {
if(hard_words.length > 9){
return hard_words;}});
alert(diff_setting.value);
if(diff_setting.value == 'Easy'){
return easy_game;
} else if (diff_setting.value == 'Medium'){
return medium_game;
} else {
return hard_game;}
}
function randomWord() {
var arr = getSelection();
answer = random_words[Math.floor(Math.random() * arr.length - 1)];
}
</script>
</body>
</html>'''
Let's start by saving the difficulty setting in a variable along these :
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
let diff_setting = 'Easy';
then edit the setdifficulty function to change that variable
function setDifficulty(difficulty) {
diff_setting = difficulty;
mistakes = 0;
guessed = [];
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
then call the function each time the setting is changed
<label for="difficulty">Choose difficulty level:</label>
<select name="difficulty" id="difficulty_setting" onchange=" setDifficulty(this.value)">
<option value="Easy" >Easy</option>
<option value="Medium">Medium</option>
<option value="Hard">Hard</option>
</select>
comment this as its not needed anymore
// var diff_setting = document.getElementById('difficulty_setting');
and correct this :
let medium_game = random_words.filter((med_words) => {
if(med_words.length <= 9 && med_words.length>=6){
return med_words;}});
as it was also selecting words that are both medium and easy
also the randomWord function used to select a word from the unfiltered array not the new one you created so it would look like this :
function randomWord() {
var arr = getSelection();
answer = arr[Math.floor(Math.random() * arr.length - 1)];
}
and finally getSelection() should look like this :
function getSelection(){
// select difficulty
//var selection = diff_setting;
let easy_game = random_words.filter((easy_words) => {
if(easy_words.length < 6){
return easy_words;}});
let medium_game = random_words.filter((med_words) => {
if(med_words.length <= 9 && med_words.length>6){
return med_words;}});
let hard_game = random_words.filter((hard_words) => {
if(hard_words.length > 9){
return hard_words;}});
alert(diff_setting);
if(diff_setting == 'Easy'){
return easy_game;
} else if (diff_setting == 'Medium'){
return medium_game;
} else if(diff_setting == 'Hard'){
return hard_game;}
}
now it should work fine :)

HTML Input doesn't allow double digits to be typed in from keyboard

I'm making a basic calculator and so far it "works". Users can only enter in a single digit from their keyboard. If they want to use double digits they're going to have to use the arrows in the text box. How can I make it so that users can enter in double digit numbers? If the user tries to type in double digit numbers the second number only get stored (so typing in 25 will only store 5)
// Base Variables
let result = 0;
let numb1 = 0;
let numb2 = 0;
let firstNumberEntered = false;
//This will be rewritten
let calculationDescription = `${numb1} + ${numb2}`;
document.querySelector('#input-number').addEventListener('keypress', numbersInput);
function numbersInput(e) {
if (!firstNumberEntered && e.key === 'Enter') {
numb1 = document.getElementById("input-number").value;
firstNumberEntered = true;
document.getElementById("input-number").innerHTML = "";
} else if (firstNumberEntered && e.key === 'Enter') {
numb2 = document.getElementById("input-number").value;
firstNumberEntered = false;
console.log(`${numb1} and ${numb2}`);
}
document.getElementById("input-number").value = "";
}
document.querySelector("#btn-add").addEventListener('click', sumNumbs);
document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs);
document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs);
document.querySelector("#btn-divide").addEventListener('click', divideNumbs);
function sumNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final + numb2Final;
calculationDescription = `${numb1} + ${numb2}`;
outputResult(result, calculationDescription);
}
function subtractNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final - numb2Final;
calculationDescription = `${numb1} - ${numb2}`;
outputResult(result, calculationDescription);
}
function multiplyNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final * numb2Final;
calculationDescription = `${numb1} x ${numb2}`;
outputResult(result, calculationDescription);
}
function divideNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final / numb2Final;
calculationDescription = `${numb1} / ${numb2}`;
outputResult(result, calculationDescription);
}
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
All this does is grab the elements on the HTML page and put them into variables and send info back to be displayed
const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
Not sure if providing my CSS is necessary, but let me know and I'll make a change.
I just started learning JavaScript recently. I watched a few videos on a Udemy tutorial on doing this project, but I stopped watching and tried to figure the rest out myself.
What I did try doing was adding maxlength="6" to my HTML input element, but that didn't work.
function numbersInput(e) {
if(!firstNumberEntered && e.key === 'Enter') {
numb1 = document.getElementById("input-number").value;
firstNumberEntered = true;
document.getElementById("input-number").innerHTML = "";
document.getElementById("input-number").value = "";
}
else if(firstNumberEntered && e.key === 'Enter') {
numb2 = document.getElementById("input-number").value;
firstNumberEntered = false;
console.log(`${numb1} and ${numb2}`);
document.getElementById("input-number").value = "";
}
}
Add document.getElementById("input-number").value = "";
to the end of both if statements and remove from the end of the function
Here's my own basic calculator using HTML, CSS, and javascript only.
To be able to input one or more digit numbers, use arrays to function as storage of those numbers chosen and for your chosen arithmetic operation as well.
please see my source code for a clearer grasp of my idea.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>My HTML/CSS/JS Calculator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="outer-container">
<div class="items" id="items"></div>
<div class="calc-screen">
<div id="screen"></div>
</div>
<div class="keys-container">
<button type="button" class="keys" id="opm" onclick="opm()">*</button>
<button type="button" class="keys" id="opd" onclick="opd()">/</button>
<button type="button" class="keys" id="opa" onclick="opa()">+</button>
<button type="button" class="keys" id="ops" onclick="ops()">-</button>
<button type="button" class="keys" id="num9" onclick="num9()">9</button>
<button type="button" class="keys" id="num8" onclick="num8()">8</button>
<button type="button" class="keys" id="num7" onclick="num7()">7</button>
<button type="button" class="keys" id="num6" onclick="num6()">6</button>
<button type="button" class="keys" id="num5" onclick="num5()">5</button>
<button type="button" class="keys" id="num4" onclick="num4()">4</button>
<button type="button" class="keys" id="num3" onclick="num3()">3</button>
<button type="button" class="keys" id="num2" onclick="num2()">2</button>
<button type="button" class="keys" id="num1" onclick="num1()">1</button>
<button type="button" class="keys" id="num0" onclick="num0()">0</button>
<button type="button" class="keys" id="del" onclick="del()">Del</button>
<button type="button" class="keys" id="clr" onclick="clr()">Clr</button>
<button type="submit" class="keys" id="equals" onclick='equals()'>=</button>
</div>
</div>
<script type="text/javascript" src="js/js.js"></script>
</body>
</html>
//js.js
var item1, op, item2, arr1, arr2, text, x, prod, qout, sum, diff, a, b, c;
item1, item2, op = '';
arr1 = [];
arr2 = [];
function num9() {
if (op=='') {
arr1.push(document.getElementById("num9").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num9").innerHTML);
arr2Function();
}
}
function num8() {
if (op=='') {
arr1.push(document.getElementById("num8").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num8").innerHTML);
arr2Function();
}
}
function num7() {
if (op=='') {
arr1.push(document.getElementById("num7").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num7").innerHTML);
arr2Function();
}
}
function num6() {
if (op=='') {
arr1.push(document.getElementById("num6").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num6").innerHTML);
arr2Function();
}
}
function num5() {
if (op=='') {
arr1.push(document.getElementById("num5").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num5").innerHTML);
arr2Function();
}
}
function num4() {
if (op=='') {
arr1.push(document.getElementById("num4").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num4").innerHTML);
arr2Function();
}
}
function num3() {
if (op=='') {
arr1.push(document.getElementById("num3").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num3").innerHTML);
arr2Function();
}
}
function num2() {
if (op=='') {
arr1.push(document.getElementById("num2").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num2").innerHTML);
arr2Function();
}
}
function num1() {
if (op=='') {
arr1.push(document.getElementById("num1").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num1").innerHTML);
arr2Function();
}
}
function num0() {
if (op=='') {
arr1.push(document.getElementById("num0").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num0").innerHTML);
arr2Function();
}
}
function opm() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opm").innerHTML;
op = '*';
console.log(op);
}
}
function opd() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opd").innerHTML;
op = '/';
console.log(op);
}
}
function opa() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opa").innerHTML;
op = '+';
console.log(op);
}
}
function ops() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("ops").innerHTML;
op = '-';
console.log(op);
}
}
function equals() {
a = parseInt(item1); b = parseInt(item2);
if (op == '*') {
prod = a * b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = prod;
document.getElementById("screen").innerHTML = c;
console.log('product: '+c);
result(c);
}
else if (op == '/') {
qout = a / b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = qout;
document.getElementById("screen").innerHTML = c;
console.log('qoutient: '+c);
result(c);
}
else if (op == '+') {
sum = a + b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = sum;
document.getElementById("screen").innerHTML = c;
console.log('sum: '+c);
result(c);
}
else if (op == '-') {
diff = a - b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+ ' =';
c = diff;
document.getElementById("screen").innerHTML = c;
console.log('difference: '+c);
result(c);
}
else {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
}
function result() {
console.log('function result: '+c);
arr1=[]; arr2=[]; item1, item2, op = '';
item1 = c;
console.log('function result new item1: '+item1);
arr1.push(item1);
arr1Function();
}
function del() {
if (arr1!='' && op=='' && arr2=='') {
arr1.pop();
console.log(arr1);
arr1Function();
}
else if (arr1!='' && op!='' && arr2=='') {
op = '';
document.getElementById("screen").innerHTML = op;
}
else if (arr1!='' && op!='' && arr2!='') {
arr2.pop();
console.log(arr2);
arr2Function();
}
}
function clr() {
arr1=[]; arr2=[]; item1,item2,op='';
console.log(arr1+', '+op+', '+arr2+', '+item1+', '+item2);
document.getElementById("screen").innerHTML = '';
document.getElementById("items").innerHTML = '';
}
function arr1Function() {
document.getElementById("screen").innerHTML = arr1;
text = ""; arr1.forEach(myFunction); text += "";
function myFunction(value) {
text += value;
x = parseInt(text);
document.getElementById("screen").innerHTML = x;
item1 = x;
console.log("Arr 1 Parse: "+x);
console.log("Arr 1: "+arr1);
console.log("Item 1: "+item1);
}
}
function arr2Function() {
document.getElementById("screen").innerHTML = arr2;
text = ""; arr2.forEach(myFunction); text += "";
function myFunction(value) {
text += value;
x = parseInt(text);
document.getElementById("screen").innerHTML = x;
item2 = x;
console.log("Arr 2 Parse: "+x);
console.log("Arr 2: "+arr2);
console.log("Item 2: "+item2);
}
}
//css
body {
background-color: orange;
}
.outer-container {
position: static;
background-color: black;
margin: auto;
border: solid black 2px;
width: 350px;
padding: 20px;
box-sizing: border-box;
border-radius: 20px;
}
.items {
background-color: silver;
border: solid white 1px;
display: inline-block;
color: black;
max-width: 100%;
font-size: 16px;
height: 20px;
box-sizing: border-box;
}
.calc-screen {
padding: 10px;
border: solid white 1px;
max-width: 100%;
width: 100%;
height: 50px;
background-color: silver;
color: white;
font-size: 25px;
box-sizing: border-box;
overflow-x: auto;
}
.keys-container {
margin-top: 20px;
width: 100%;
border: solid white 1px;
max-width: 100%;
display: inline-block;
}
#equals {
width: 100%;
}
.keys {
float: left;
border: solid black 1px;
box-sizing: border-box;
width: 25%;
height: 40px;
box-sizing: border-box;
text-align: center;
margin: auto;
font-size: 25px;
padding: 5px;
}
.keys:hover {
background-color: blue;
color: white;
}

how to get different winning% in decreasing order for number of winners?

var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
var set = document.getElementById('winnerCount').value;
if (set.length > sum.length) {
document.getElementById('err_winnerCount').remove();
} else {
document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
document.getElementById("demo").innerHTML = "Rank &nbsp &nbsp Winning% &nbsp &nbsp &nbsp &nbsp &nbsp Winning Amount";
var x = document.getElementById("w_amount").value;
var w = document.getElementById("c_size").value;
var y = document.getElementById("winnerCount").value;
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
for (z = 1; z <= parseInt(y); z++) {
document.getElementById("demo1").innerHTML += +z + "&nbsp<input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/>&nbsp<input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert('errr');
$('#err_winnerCount').innerHTML = "Please enter less than contest size";
}
}
var sharePerc = 0;
function getValues(arg) {
var id = arg.getAttribute('id');
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var curPerc = document.getElementById(id).value;
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - curPerc) / (x2.length - 1);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" onblur="validate()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="2"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"></input><span class="err" id="err_winnerCount"></span></li>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</div>
// firstly when giving winning amount and contest size we get the entry fee and after check in customize winning it will enable the set number of winners and set button.In set number of winners the input should be less than the contest size but while entering the greater than contest size it will not showing error message and after clicking set button we get a list of winners in this the winning % should be decreasing order while changing the default winning % of first text box but in my code while changing the second text box it changes the first text box also. if possible please know me how to solve this.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
$('#err_winnerCount').html("");
var set = document.getElementById('winnerCount').value;
var contestSize = document.getElementById('c_size').value;
if (set > contestSize) {
$('#err_winnerCount').html("");
} else {
//document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
var x = document.getElementById("w_amount").value;
var w = parseInt(document.getElementById("c_size").value);
var y = parseInt(document.getElementById("winnerCount").value);
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
//document.getElementById("demo").innerHTML = "Rank &nbsp &nbsp Winning% &nbsp &nbsp &nbsp &nbsp &nbsp Winning Amount";
var demoTableBody = document.getElementById("demo_table").tBodies[0];
demoTableBody.innerHTML = "";
//console.log(demoTableBody.innerHTML);
for (z = 1; z <= parseInt(y); z++) {
//console.log(demoTableBody.children.length);
var rowIndex = demoTableBody.children.length + 1;
var newRow = "<td>"+rowIndex+"</td>";
newRow += "<td><input type='text' class='tot' id='perc" + rowIndex + "' value='' onkeyup='getValues(this)'/><span class = 'perc_error_spn' id='perc_error" + rowIndex + "'></span></td>";
newRow += "<td><input type='text' class='pop' id='val" + rowIndex + "' value='Rs." + a + "'/></td>";
demoTableBody.innerHTML += newRow;
//document.getElementById("demo1").innerHTML += +z + "&nbsp<input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/>&nbsp<input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert("errr");
$('#err_winnerCount').html("Please enter less than contest size");
}
}
var sharePerc = 0;
function getValues(arg) {
// clear all error messages.
var errorSpans = document.getElementsByClassName("perc_error_spn");
for(var i = 0; i < errorSpans.length; i++){
errorSpans[i].innerHTML = "";
}
var id = arg.getAttribute('id');
var row_index = arg.parentNode.parentNode.rowIndex;
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var tmp = 0;
var previousWinnersPercentage = [];
var nextWinnersPercentage = [];
for(var i = 1; i < row_index; i++){
tmp += parseFloat(document.getElementById("perc" + i).value);
previousWinnersPercentage[previousWinnersPercentage.length] = tmp;
}
for(var i = row_index + 1 ; i <= x2.length; i++){
nextWinnersPercentage[nextWinnersPercentage.length] = parseFloat(document.getElementById("perc" + i).value);
}
//winAmt -= tmp;
var curPerc = document.getElementById(id).value;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var isInvalidInput = isBiggerThanPreviousPercentage(previousWinnersPercentage,curPerc);
if(!isInvalidInput){
isInvalidInput = isLesserThanPreviousPercentage(nextWinnersPercentage,curPerc);
}
if((sharePerc <= 0 && x2.length > 1) || isInvalidInput){
var errorSpan = id.replace("perc", "perc_error");
document.getElementById(errorSpan).innerHTML = "Invalid input";
return;
}
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = row_index; i <= x2.length; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
function reorderPercentage(){
var demoTableBody = document.getElementById("demo_table").tBodies[0];
for(var i = 0; i < demoTableBody.children.length; i++){
var percentageInput = demoTableBody.children[i].querySelector(".tot");
//console.log(percentageInput.value);
var row = percentageInput.parentNode.parentNode,
sibling = row.nextElementSibling,
parent = row.parentNode;
var siblingPercentageValue = "";
//console.log(sibling);
if(sibling != null){
siblingPercentageValue = sibling.querySelector(".tot").value;
}
if(percentageInput.value < siblingPercentageValue){
parent.insertBefore(sibling,row);
}
}
}
function isBiggerThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value > e){
return true;
}
});
return result;
}
function isLesserThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value < e){
return true;
}
});
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="3"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"/><span class="err" id="err_winnerCount"></span>
<input type="button" value="Reorder" onclick="reorderPercentage();"/>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<table id="demo_table">
<thead>
<tr>
<th>Rank</th>
<th>Winning %</th>
<th>Winning Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
table, th, td {
border: 1px solid black;
}
</style>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">10 Winners</button>
<div class="dropdown-content">
<table style="width:100%">
<tr>
<th>Rank</th>
<th>Prize</th>
</tr>
<tr>
<td>1</td>
<td>1000</td>
</tr>
<tr>
<td>2-5</td>
<td>500</td>
</tr>
<tr>
<td>6-10</td>
<td>100</td>
</tr>
</table>
</div>
</div>
</body>
If you input number of winners greater than contest size it will prompt an alert box. Check and let me know that is it working or not?
Due to below code both the text boxes are modified simultaneously.
If you can explain the below code, why you are using this
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}

Javascript: Currency converter

Im new in javascript and I'm trying to make a simple currency converter, it is working fine when I select "£Pound" "£Pound" or "£Pound" "R$Real" but when I select "R$Real" "R$Real" runs the "Pound" "R$Real" calculation.
I spent hours trying to figure this out (very frustrating).
How to fix it? Is there another way to do it? (also tried using " if " and " else if " same issue). Thanks!
Here`s the HTML:
<label>Amount:</label>
<input type="text" id="amount" />
<label>From:</label>
<select id="select1">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<label>To:</label>
<select id="select2">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<input type="button" onClick="calculation()" value="calculate" />
<div id="result"></div>
Here`s the JS:
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch((currency1)&&(currency2)){
case "pound":
case "pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound":
case "real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}}
To fix your JS do the following:
The issue is that your switch would compute to a single string, and you are using fall-through switch statements, jsFiddle to demonstrate what I mean.
Switch Statement Documentation for JavaScript
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch (currency1 + ' ' + currency2) {
case "pound pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}
}
Use the below to display the number and then just put the symbol in front, as this code will add commas and separators in the right spots, including negative.
Format number to currency:
function formatCurrency(num, precision) {
//identify '(123)' as a negative number
if (typeof num == 'string' && num.toString().indexOf('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && precision === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
if (num === '' || (num === '-' && precision === -1)) {
return;
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (precision >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(precision); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
if ((hasDecimals && precision == -1) || precision > 0) {
num += '.' + decimals;
}
// format symbol/negative
var format = isPositive ? '%s%n' : '(%s%n)';
var money = format.replace(/%s/g, '$');
money = money.replace(/%n/g, num);
return money;
}
console.log(formatCurrency(12002031203120, 2))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<style>
body{
background:linear-gradient(3150deg,#7458ff,#a48afc);
background-size: cover;
height: 800px;
display: flex;
align-items: center;
justify-content:center;
}
.col-md-8{
background-color: rgb(183, 170, 170);
padding: 10px 24px;
border-radius: 20px;
width: 490px;
}
.form-group{
width: 100%;
display: flex;
}
input{
width:95%;
color:aliceblue;
height: 40px;
font-size: 1em;
margin: 0.2em 0;
border-radius: 10px;
border: none;
background: #676666;
outline: none;
padding: 0.1em;
}
select{
width: 50%;
height:40px;
font-size: 30px;
cursor: pointer;
background: #039cfb;
outline: none;
color: black;
padding: 0 1em;
border-radius: 10px;
border: none;
}
</style>
</head>
<body>
<div class="col-md-6 well">
<h3 class="text-primary">Javascript - Simple Currency Converter</h3>
<hr style="border-top:1px dotted #ccc;">
<div class="col-md-8">
<h4>Converter</h4>
<hr style="border-top:1px groovy #ccc;"/>
<div class="form-group">
<select onchange="Currency(); Calculate()" class="form-control" id="converter" style="width:30%;">
<option value="Dollar">Dollar</option>
<option value="Pound">Pound</option>
<option value="Euro">Euro</option>
<option value="Yen">Yen</option>
<option value="Yuan">Yuan</option>
</select>
<br />
<input type="number" oninput="Calculate()" class="form-control" id="value1"/>
</div>
<br /><br />
<div class="form-group">
<label>Pak Rupee:</label>
<input type="number" class="form-control" id="value2" disabled="disabled"/>
</div>
</div>
</div>
<script>
function Currency(){
y = document.getElementById("converter").value;
return y;
}
function Calculate(){
y = Currency();
x = document.getElementById("value1").value;
if(x == ""){
document.getElementById("value2").value = "";
}else{
switch(y){
case "Dollar":
document.getElementById("value2").value = x * 215.99;
break;
case "Pound":
document.getElementById("value2").value = x * 72.39;
break;
case "Euro":
document.getElementById("value2").value = x * 63.84;
break;
case "Yen":
document.getElementById("value2").value = x * 0.49;
break;
case "Yuan":
document.getElementById("value2").value = x * 8.20;
break;
}
}
}
</script>
</body>
</html>

Categories