I'm trying to validate the value found the in the radio button when the submit button is clicked. I'm not sure of the proper syntax, this is what I've pieced together from what I've found online so far.
$(document).ready(function(){
alert('testing');
// Create array to traverse so that on clicking submit, the current question
//is deleted, and the next question in the array is loaded.
var questionsArray = [];
//Create counters for both correct answers and current question
var correctAnswers = 0;
var currentQuestion = 0;
//String to use for messages
var rightAnswer = "That's correct! You have " + correctAnswers + " out of 10 correct!";
var wrongAnswer = "Oh dear, that's so so wrong! You have " + correctAnswers + " out of 10 correct";
//Contructor Function to create questions
function Question (question, choices, answer){
this.question = question;
this.choices = choices;
this.answer = answer;
}
//Question Creations
questionsArray.push(new Question('Who is the Flash', ['Walter White', 'Johnny Cage', 'Barry Allen', 'Peter Parker'], 'Barry Allen'));
//Testing:
$('.q_question').append(questionsArray[0]['question']);
$('.btn1').after(questionsArray[0]['choices'][0]);
$('.btn2').after(questionsArray[0]['choices'][1]);
$('.btn3').after(questionsArray[0]['choices'][2]);
$('.btn4').after(questionsArray[0]['choices'][3]);
$('#submit').on('click', function(){
alert('click!'); //Test to make sure the click on submit is being recorded.
currentQuestion ++;
var answer = $('input[name="1"]:checked').val(); //The .val() is new to me, pretty sure this is where I've gone wrong
if(answer == questionsArray[0]['answer']){
correctAnswers ++;
$('.jumbotron').append(rightAnswer);
} else {
$('.jumbotron').append(wrongAnswer);
}
});
});
HTML:
<!doctype html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href='css/css.css'>
<title>Super Awesome Quiz!</title>
</head>
<body>
<header class="header">
<h1 classs = "title">Welcome to My Super Awesome Quiz!!</h1>
<h3 class="question_counter">Ver. 1.1</h3>
</header>
<form class = "question">
<h2 class= "q_title"> </h2> <!-- Will use questionCounter here once created -->
<h3 class="q_question"></h3>
<input class='btn btn1' type="radio" name="1" value="answer" >
<br>
<input class='btn btn2' type="radio" name="1" value="answer" >
<br>
<input class='btn btn3' type="radio" name='1' value='answer' >
<br>
<input class='btn btn4' type="radio" name='1' value='answer' >
<br>
<input id="submit" type='submit' name='1' value='Submit'>
<br>
</form>
<div class='jumbotron'>
<h2></h2>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js.js" type="text/javascript"></script>
</body>
</html>
Problem is you're not updating the value of the radio input:
$('.q_question').append(questionsArray[0]['question']);
$('.btn1').after(questionsArray[0]['choices'][0]);
$('.btn1').val(questionsArray[0]['choices'][0]); // set value to option value
...
This will cause the value of the input to hold the actual value which can be compared to the correct answer.
Another option is to compare to the value of the text after the radio button.
Related
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used name="items[]" to get the values i was wondering if there is a way to use ID or Class instead of the name.Any help would be appreciated in advance .
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate()
{
initVariable();
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.innerHTML +=count;
taxFeild.innerHTML+=(parseFloat(tax*count));
Total.innerHTML+= (tax*count) + count;
}
btn.addEventListener('click',Calculate);
function initVariable()
{
count =0;
ItemTotal.innerHTML="Item Total: ";
taxFeild.innerHTML =" Tax: ";
Total.innerHTML ="Total with Tax: ";
}
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>
<head>
<title>Test</title>
</head>
<body>
<div class = "container">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
</div>
<button id="btn">Calculate</button>
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</body>
</html>
If you have more than one its not correct to use same ID.
you can use de class and select it with document.querySelectorAll('.items')
The possible variants could be to use querySelectorAll or getElementsByClassName:
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)
<input type="checkbox" class="items" value='7.99' id="item1"> Hamburger ($7.99)
const checkboxes = document.getElementsByClassName('items');
// OR
const checkboxes = document.querySelectorAll('.items');
Or you still could use name attribute on input (instead of class):
const checkboxes = document.querySelectorAll('input[name="items[]"]');
You can select elements by their class. I would recommend using jQuery for this, but it can also be done in pure JavaScript. Let's assuming that we have three basic checkboxes (this is pseudo code):
<input type="checkbox" class="form-control" value="7.99">
<input type="checkbox" class="form-control" value="9.99">
<input type="checkbox" class="form-control" value="8.99">
<button class="btn btn-primary" type="button">
Calculate
</button>
We could use jQuery to iterate over each element with the class name ".form-control" in this scenario:
$(document).ready(function() {
const tax = 0.05;
$('.btn').on('click', function() {
let total = 0;
$('.form-control').each(function() {
if($(this).is(':checked')) {
let val = parseFloat($(this).val());
total += val;
}
});
if(total > 0) {
total += tax;
alert('Your total is $' + total);
}
});
});
Without jQuery you would do something such as:
const checks = document.getElementByClassName('form-control');
and then you could run an checks.each();
As a side not, do not give elements the same ID name or else JavaScript will not know which element you are trying to select. If you are going to select elements based on their id, make sure they have different ID's.
Been coding for a few weeks now, i'm trying to write a simple pizza picker with constructor and prototype.
I wrote 4 radio buttons with 4 different pizzas
Console log doesn't show any errors, but when it's time to order the price should appear on my results ID but it's not.
I'm guessing my prototype function is the reason why, but I wrote it very simply and I don't understand why it's not working.
Here is my JS
function Pizza(){
this.type = [];
this.price = [];
}
Pizza.prototype.newOrder = function() {
if(this.type === 1){
this.price + 5;
return
}
if(this.type === 2){
this.price + 7;
return
}
}
$(document).ready(function() {
var customer = new Pizza();
$("button#order").click(function(event) {
$("input:checkbox[name=pizza]:checked").each(function(event){
customer.newOrder();
$("#price").append(customer.price);
});
});
})
My HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>ORDER PIZZA</title>
</head>
<body>
<div class"container">
<h1>ORDER PIZZA</h1>
<form id="pizza-form">
<div class="form-group">
<p>Pick a pizza</p>
<input type="checkbox" name="pizza" value="1">Small1 <br>
<input type="checkbox" name="pizza" value="2">small2<br>
<input type="checkbox" name="pizza" value="3">large1<br>
<input type="checkbox" name="pizza" value="4">large2<br>
</div>
</div>
<button id="order" type="submit">ORDER</button>
</form>
<h2 id="price"> Total: </h2>
</body>
</html>
I completely agree with #jdv's comment above w.r.t learning some new debugging skills.
A few mistakes:
When you call customer.newOrder, within that function this.type's value is still it's initial value of [] that you set in the constructor. You need to pass the selected value from the checkbox to the newOrder function as an argument. Note that the values of your checkboxes are of type String and not Number. Check the docs for JQuery each
this.price + 5 is not the correct way to increment the value of in Javascript. It should be this.price = this.price + 5 or this.price += 5 for short.
You need to reset the price to 0 every time to click on the button so it does not add the price to the previous order's price.
I am posting a probable solution to your problem, but this solution is worth nothing compared to having the skills to debug and read documentation, so I would encourage you to figure it out by yourself and not follow this solution -
function Pizza(){
this.type = '';
this.price = 0;
}
Pizza.prototype.newOrder = function(pizzaType) {
this.type = pizzaType
if (this.type === '1') {
this.price = this.price + 5;
}
if (this.type === '2') {
this.price = this.price + 7;
}
}
$(document).ready(function() {
var customer = new Pizza();
$("button#order").click(function(event) {
customer.price = 0
$("input:checkbox[name=pizza]:checked").each(function(index, checkbox){
customer.newOrder(checkbox.value);
});
$("#price").html(customer.price);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>ORDER PIZZA</title>
</head>
<body>
<div class"container">
<h1>ORDER PIZZA</h1>
<form id="pizza-form">
<div class="form-group">
<p>Pick a pizza</p>
<input type="checkbox" name="pizza" value="1">Small1 <br>
<input type="checkbox" name="pizza" value="2">small2<br>
<input type="checkbox" name="pizza" value="3">large1<br>
<input type="checkbox" name="pizza" value="4">large2<br>
</div>
</form>
<button id="order">ORDER</button>
<h2 id="price"> Total: </h2>
</div>
</body>
</html>
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate (form)
{
cel = fah * 0.5555 - 32;
document.getElementById("finish").innerHTML = cel;
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius! <br>
<input type="number" name="fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
</html>
Edit1: Moved the inner.HTML into the Function
So the reset button is the only thing that works. Is it possible to calculate the math this way?
You asked a question on how to create a pizza form a while ago and you deleted it soon as it was down voted a few times.
The point to note here is, it is okay if a few people dislike your question. You've joined StackExchange not to gain points but to learn a few things. Your question could be helpful to a lot of others out there in this world. So here it is the answer to your pizza question
<html>
<body>
<p>A pizza is 13 dollars with no toppings.</p>
<form action="form_action.asp">
<input type="checkbox" name="pizza" value="Pepperoni" id="pep">Pepperoni + 5$<br>
<input type="checkbox" name="pizza" value="Cheese" id="che">Cheese + 4$<br>
<br>
<input type="button" onclick="myFunction()" value="Send order">
<input type="button" onclick="cost()" value="Get cost">
<br><br>
<input type="text" id="order" size="50">
</form>
<script>
function myFunction() {
var pizza = document.forms[0];
var txt = "";
var i;
for (i = 0; i < pizza.length; i++) {
if (pizza[i].checked) {
txt = txt + pizza[i].value + " ";
}
}
document.getElementById("order").value = "You ordered a pizza with: " + txt;
}
function cost() {
var pep = 5;
var che = 4;
var pizza = 13;
var total = 0;
if (document.getElementById("pep").checked === true) {
total += pep;
}
if (document.getElementById("che").checked === true) {
total += che;
}
document.getElementById("order").value = "The cost is : " + total;
}
</script>
</body>
</html>
Thanks. I hope this helps you.
Adeno Fixed it by declaring what fah was. you can also see your errors with f12.
https://stackoverflow.com/users/965051/adeneo
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate(form) {
var cel = (document.getElementById("fah").value -32) * 5 / 9;
document.getElementById("finish").innerHTML = cel;
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius!
<br>
<input type="number" name="fah" id="fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
You never get the value from the input type = "number"
Try this
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
function calculate()
{
var fah = document.getElementById('fah').value;
var cel = parseFloat(fah * 0.5555 - 32);
document.getElementById("finish").innerHTML = cel;
}
</script>
</head>
<body>
<form>
Turn Fahrenheit to Celsius! <br>
<input type="text" name="fah" id="fah">
<input type="button" name="button" value="calculate" onClick="calculate()">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
</html>
Couple things: You need to set the innerhtml from within the function because the variable is in the function. Or you could have declared the variable outside the function first like var fah = "" then the function. But since you declared it in the function only the function can see it. So i moved the innerhtml set into the function.
Also, javascript likes to use id's not name = "fah" You can call an element by name but id is easier.
i rounded it to integer. you would get 9 decimals your way.
Lastly, innerhtml set clears all the html so you would lose the °C the way you had it.
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate (form)
{
var fah = this.fah.value;
cel = Math.round((fah-32) / 1.8);
document.getElementById("finish").innerHTML = cel+"°C";
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius! <br>
<input type="number" name="fah" id = "fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish"></p>
</body>
</html>
Currently working on an "retirement calculator" where I have to generate a table for money-saved each year based on data entered into the first two forms. Unfortunately I can't figure out why it's not appending the table to the site. I don't receive any errors on the console.
I'm also a complete novice at JS/JQ. The code for calculate is near the bottom. I realize it may look at little all over the place, I'm trying to get it to work first before I got back and clean it up some.
EDIT: I took out some methods so there isn't so much to traverse. Assume that the variables involved in calculate are set to real values (aka they're not null/NaN).For example there's an add JQuery method that'll add more scenarios. But since it distracts from the problem I took it out. But the for loop runs in relation to the array
var scenarioCount=0;
var hasError=false
var error=false;
var YOB;
var CurrSav;
var RetAge;
var LifeExp;
var Year;
var scenarios = new Array();
$(document).ready(function ()
{
$('#calculate').on('click', function(e)
{
if(!isBasicInfoValid()) //check to see if basic info is correct
{
if(!error) //if there isn't already an error put one
{
$('#basic').append($("<div class='basicError'>Input is not valid! </div>"));
}
resetVars(); //reset the variables
error=true; //say there is an error on screen
}
else
{
$("#basic .basicError").remove();
error=false;
calculate();
}
e.preventDefault();
});
});
function calculate()
{
var body = document.getElementById('body');
//body is null right here for some reason
$(body).append("<div id='results' class='form'>");
for(var i=0;i<scenarios.length;i++)
{
var element = scenarios[i];
var n = parseInt(YOB)+parseInt(RetAge)-Year;
var m = LifeExp-RetAge;
var r = 1+element.workRate;
var g = 1 + element.retiredRate;
var I = CurrSav;
var T = element.retIncome;
var part1 = (T/Math.pow(g,m-1))*((1-Math.pow(g,m))/(1-g))-(I*Math.pow(r,n));
var S = part1*(1-r)/(1-Math.pow(r,n));
var savings=I;
$('#results').append("<div><h4>You need to save "+S+" dollars</h4></div>")
$('#results').append("<table id=t><tr><th>Year</th><th>Money Saved</th></tr>");
for(var j=n;j>0;j--)
{
savings=S+savings*r;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
for(var j=m;j>0;j--)
{
savings=(savings-T)*g;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
$('#results').append("</table></div>");
}
};
function resetVars()
{
YOB=null;
CurrSav=null;
RetAge=null;
LifeExp=null;
Year=null;
}
function scenarioObject()
{
var obj={
nameScen : document.forms["scenario"]["ScenarioName"].value,
workRate : document.forms["scenario"]["Working"].value,
retiredRate : document.forms["scenario"]["Retired"].value,
retIncome : document.forms["scenario"]["desiredInc"].value
}
return obj;
}
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3</title>
<link rel='stylesheet' type='text/css' href='/uncSemester7/comp426/a3/assignment3.css'>
<script src='/uncSemester7/comp426/a3/jquery-1.10.2.js'></script>
<script src='/uncSemester7/comp426/a3/assignment3.js'></script>
</head>
<body>
<div class='form'>
<h3> Basic Information </h3>
<form id='basic'>
<div>Year of Birth: <input type='number' name='YOB'> </div>
<div>Current Savings: <input type='number' name='CurrSav'>
</div>
<div>Expected Retirement Age: <input type='number' name='RetAge'></div>
<div>Life expectancy: <input type='number' name='LifeExp'>
</div>
</form>
</div>
<div id='scenDiv' class='form'>
<div id='buttons'>
<div><button id='add' type='submit'>Add Scenario </button></div>
<div><button id='calculate' type='submit'> Calculate </button></div>
</div>
<h3> Scenario </h3>
<form id='scenario'>
<div>Name: <input type='text' name='ScenarioName'> </div>
<div>Rate of Investment Return (While Working): <input type='number' name='Working'></div>
<div>Rate of Investment Return (Retired): <input type='number' name='Retired'></div>
<div>Desired Retirement Yearly Income: <input type='number' name='desiredInc'></div>
</form>
</div>
</body>
</html>
You're using getElementById('body'), where you should be using getElementsByTagName('body')[0], as body is not an id, but a tag. Or better yet with jQuery since you're already using it, $('body').
Here is the sample code for my project. It contains two forms on a single page.
The first form contains username and a textbox, when I enter the username and click the login button the user's name should be displayed and the logout form should be displayed.
How do I ensure that the user will remain logged in once the browser window is closed?
Code
<!DOCTYPE html>
<html>
<title>Login Page</title>
<head>
<script>
function set(x)
{
document.getElementById(x).value="";
}
</script>
<script>
function showDiv(e)
{
var divs = document.getElementsByTagName('div');
if (e==1)
{
for(i=0;i<divs.length;i++)
{
if (divs[i].id=="hidevar1")divs[i].style.visibility="visible";
else if (divs[i].id=="hidevar2")divs[i].style.visibility="hidden";
}
}
else {
for(i=0;i<divs.length;i++)
{
if (divs[i].id=="hidevar1")divs[i].style.visibility="hidden";
else if (divs[i].id=="hidevar2") {
divs[i].style.visibility="visible";
}
}
}
}
function put()
{
var x = document.getElementById("fname").value;
currentTime=new Date();
if(currentTime.getHours()<12)
var y = "Good Morning ";
else if(currentTime.getHours()<17)
var y = "Good Afternoon ";
else
var y = "Good Evening ";
document.getElementById("devin").innerHTML = "Hello " + x + " " + y;
}
</script>
<script>
</script>
<script>
function search()
{
var dic = document.getElementById("url").value;
var str="http://www.google.co.in/#hl=en&q=";
var www=str+dic;
window.open(www);
}
</script>
</head>
<body>
<div id="devin">
</div>
<div id="hidevar1" style="visibility: visible;">
<form name="frm1" method="post" >//Login form
User Name : <input type="text" id="fname" value="Enter name here" onfocus="set(this.id)" >
</form>
<input type="button" value="Login" onClick="showDiv(2);put();">
</div>
<div id="hidevar2" style="visibility: hidden;">
<form name="frm2">//logout form
<script>
</script><br/>
<input type="submit" value="logout">
<br>
<br>
</form>
</div>
<br><br>
<input type="text" name="url1" id="url" />
<input type="submit" value="google"onclick="search();" />
</body>
</html>
If you plan to use spring, spring-security provides remember me services which would let you be logged in across browsers or sessions.
Other option is to use Apache shiro if you find spring-security too complex for your application.