Javascript Quiz with HTML + CSS [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
****This code is now working.
Thankyou for your input everyone.
The initial problem was that the code would run on page load, and then the second problem was that it refreshed the page on submit
After some input from a few individuals we were able to debug it together and I learned some new things.****
function check(){
let correctAns1 = 'carname = "volvo"';
let input = document.getElementById("q1").value;
let score=0;
if(input.toLowerCase() == correctAns1) {
score++;
alert("That is correct")
alert("You have a total of " + score + " points")
}else{
alert("Incorrect")
};
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
});
<div id="testForm">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1" value><br>
<input type="submit" value="Submit">
</form>
</div>

You can keep questions, scores in localstorage in JavaScript.
This information is stored in the browser and works like cookies.
ex: value inserting in localstorage:
localStorage.setItem('myCat', 'Tom');
ex: accessing to value from localstorage:
localStorage.getItem('myCat');
You Can Look:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

I think you are troubled by that empty screen after submission, if yes, then the reason for that is "On form submit the page gets refreshed/redirected" to stop that use onsubmit = "check(); return false" or handle it with js using event.preventDefault.
Using return false:
onsubmit = "check(); return false"
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
};
check();
<div id="question1">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
Using preventDefault and javascript onsubmit:
e.preventDefault();
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
return false
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
check();
});
<div id="question1">
<form id="testForm" ><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
For storing, you can use localstorage on client-side. You can have an array/object of questions and answers and convert it into a string using JSON.stringify and store it in localstorage
localStorage.setItem('questionBook', JSON.stringify(questionBookObject));
and retrieve it using getItem and then JSON.parse it to get the object back.
const questionBookObject = localStorage.getItem('questionBook');

Related

Cant get my input value to appear on my functions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want my use to enter a value and when they press Submit Calculations there should be a alert bar previewing an error message if value is null.
<form id= "form1" class = "myform" action ="register.php" method "post">
<label> Loan Amount: </label>
<input type = "text" class= "inputvalues" id = "loanAmm" placeholder = "Fill in the Details"> <br>
<input name = "submit_btn" type ="button" onclick = "checkvalues();" id = "storevalue" value = "Submit Calculations"> <br>
</form>
function checkvalues()
{
var loanAmount = document.forms["form1"]["loanAmm"].value;
if (loanAmount == null )
{
alert("Re-enter value");
return false;
}
}
When referencing elements with document.forms["form1"], "form1" is the name of the form, not the id. The same is true for document.forms["form1"]["loanAmm"] - "loanAmm" is the name of the input.
Best practice is to use the id to reference the input.
Also, use addEventListener to add the onclick handler because it separates the logic from the layout.
document.getElementById("storevalue").addEventListener("click", function() {
var loanAmount = document.getElementById("loanAmm").value;
if (loanAmount.trim() === "") {
alert("Loan amount cannot be blank");
return false;
} else {
document.getElementById("form1").submit();
}
});
<form id="form1" class="myform" action="register.php" method "post">
<label> Loan Amount: </label>
<input type="text" class="inputvalues" id="loanAmm" placeholder="Fill in the Details"> <br>
<input name="submit_btn" type="button" id="storevalue" value="Submit Calculations"> <br>
</form>
Your test should be :
if (loanAmount === '') {
alert("Re-enter value");
return false;
}
If input is empty, the value is not null but empty.

First time, password field [duplicate]

This question already has answers here:
Javascript if syntax
(5 answers)
Closed 5 years ago.
It's fixed now.
It's basically a textbox that when the right text is entered should cause something to happen, i have code for it, this is my first time playing around with html. It's not really for anything and just for fun
<body>
<center>
<input id="passfield" type="text" value="" />
<input id="check" type="button" value="Check" onclick="check();"/>
<script>
var field = document.getElementById("passfield").value;
var pass = "password";
function check() {
if field === pass then {
window.location.href = 'the site i want it to go to';
};
};
document.getElementById("check").onclick = check();
</script>
<center>
</body>
The console says: check() isn't a function
You have a couple problems:
You should move the variables field and pass into the function, so that they're defined when the function is called. Otherwise, they won't update - which means field will always be empty (since it was set as soon as the page loaded, when the input's value was '')
Add an event listener in your Javascript, rather than using the 'onclick' attribute. It's nicer because it keeps all of your Javascript together, and you won't have to skim through your HTML every time you hit a JS error.
You have some formatting issues - the if in particular should use the following syntax:
if (condition) {
then do this
} else {
do this
}
You can check out this example on CodePen.
<body>
<center>
<input id="passfield" type="text" value="" />
<input id="check" type="button" value="Check" />
<center>
<script>
function check() {
var field = document.getElementById("passfield").value;
var pass = "password";
if (field === pass) {
window.location.href = "the site i want it to go to";
}
}
document.getElementById("check").addEventListener('click', check)
</script>
</body>

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

HTML/Javascript Page is resetting after submitting form

I am working on learning to make forms using HTML and Javascript. When I go to submit my form, it processes it, and I can see the result, but the page quickly resets so that the form is back to its starting state. How can I make sure the page doesn't reset when the function is done?
Here is the HTML for the form and the function that processes it:
<form name="calculator" onsubmit="return calculate(this);">
Enter the value of the house: $
<input type="text" name="homeValue" id="homeValue" size="7" /><br>
<select name="selMortgage" id="selMortgage">
<option>Select a mortgage length</option>
<option>15-year mortgage</option>
<option>30-year mortgage</option>
</select></br>
<p class="form"><input type="checkbox" name="chkDiscount" value="discount"/>Good Credit Discount?</p>
<input type="submit" value="Calculate" />
<div id="result"></div>
</form>
function calculate(form) {
var amountEntered = form.homeValue.value;
var termLength;
var interestRate;
var calc;
document.getElementById("result").innerHTML = "hi";
if (!/^\d+(\.\d{1,2})?$/.test(amountEntered))
{
alert("You did not enter an amount of money");
//form.homeValue.focus();
return;
}
if (form.chkDiscount.checked == true)
{
interestRate = .05;
}
else
{
interestRate = .06;
}
if (form.selMortgage.selectedIndex == 0)
{
alert("Select a mortgage length");
}
else if (form.selMortgage.selectedIndex == 1)
{
termLength = 15;
}
else if (form.selMortgage.selectedIndex == 2)
{
termLength = 30;
}
calc = (Math.pow(1+interestRate,termLength) * amountEntered)/(termLength*12);
document.getElementById("result").innerHTML = calc.toFixed(2);
}
It looks like you are missing a return false.
Since you are submitting the form the values are lost due to page reload.
You may try to POST your values then assign the post values on your form elements so that even after refresh youre still able to see the POST data submitted..
Try this:
Just use return false; at the end of your javascript function.
When the form is submitted, the JS function calculate will be invoked. Since the function does not return any value, undefined will be assumed. And in JS the undefined will be assumed to nothing and the form will be submitted to server and reload again. This is why you lose your data. From your code, the page just execute some JS code. So we can prevent submitting the form to keep your data. You may need to return false in calculate function to prevent submitting. Example as below:
document.getElementById("result").innerHTML = calc.toFixed(2);
return false;

Checkbox js toggling incorrectly

I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>​
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2

Categories