personalty quiz- radio type and value - javascript

I'm trying to make personalty quiz in HTML with javascript(no jquery)and I don't know where is my problem.
I know I need to put return false but I don't know were
I don't know how to use value well
function count() {
var first = document.querySelector('input[name=first]').value;
var second = document.querySelector('input[name=second]').value;
var dps = 0;
var tank = 0;
var sup = 0;
if (first == 'dps') {
dps++;
}
if (first == 'tank') {
tank++;
}
if (first == 'sup') {
sup++;
}
if (second == 'dps') {
dps++;
}
if (second == 'tank') {
tank++;
}
if (second == 'sup') {
sup++;
}
var count2;
if (dps > tank && dps > sup) {
count2 = "dps";
}
if (tank > dps && tank > sup) {
count2 = "tank";
}
if (sup > dps && sup > tank) {
count2 = "sup";
}
var result = document.getElementById("motek");
result.innerText = count2;
}
<form id='hello' onsubmit="count()">
<h3>what your favorite food?</h3>
<input type="radio" name="first" value="tank">hghjghj<br>
<input type="radio" name="first" value="dps">hghjfgsfghj<br>
<input type="radio" name="first" value="sup">hghsgdsdqqwj<br>
<h3>what your favoritsfde food?</h3>
<input type="radio" name="second" value="tank">hghfsghj<br>
<input type="radio" name="second" value="dps">hghesfghj<br>
<input type="radio" name="second" value="sup">hghsfdqwj<br>
<input type="submit" value="submit">
</form>
<div id="motek">
</div>

You need to stop the page from reloading.
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
In pure Javascript, you can also use: e.preventDefault()
OR you can make your <button type="button">Submit</button> type as button and handle form submit manually on click of this button.
The snippet below shows return false approach.
function count() {
var first = document.querySelector('input[name="first"]:checked').value;
var second = document.querySelector('input[name="second"]:checked').value;
var dps = 0;
var tank = 0;
var sup = 0;
if (first == 'dps') {
dps++;
}
if (first == 'tank') {
tank++;
}
if (first == 'sup') {
sup++;
}
if (second == 'dps') {
dps++;
}
if (second == 'tank') {
tank++;
}
if (second == 'sup') {
sup++;
}
var count2;
if (dps > tank && dps > sup) {
count2 = "dps";
}
if (tank > dps && tank > sup) {
count2 = "tank";
}
if (sup > dps && sup > tank) {
count2 = "sup";
}
var result = document.getElementById("motek");
result.innerText = count2;
}
<form id='hello' onsubmit="count(); return false">
<h3>what your favorite food?</h3>
<input type="radio" name="first" value="tank">hghjghj<br>
<input type="radio" name="first" value="dps">hghjfgsfghj<br>
<input type="radio" name="first" value="sup">hghsgdsdqqwj<br>
<h3>what your favorite food?</h3>
<input type="radio" name="second" value="tank">Tank<br>
<input type="radio" name="second" value="dps">DPS<br>
<input type="radio" name="second" value="sup">SUPP<br>
<input type="submit" value="submit">
</form>
<div id="motek">
</div>

Related

How do I create an outcome quiz using html and JavaScript?

I've been trying to create a quiz and all the examples of quizzes I can find are scored mathematically with numerical values set for each answer. This is my attempt to create a "What ____ are you?" outcome quiz. What am I missing to make this work or how can I fix this code to make it more efficient? Thanks.
Edit: The problem is that it doesn't display a result after submission.
<HTML>
<HEAD>
<TITLE>
Title Of Quiz
</TITLE>
</HEAD>
<BODY>
Title of Quiz
<!--Quiz itself will go here-->
<form action="/results" method="post">
<!--This is where the questions go-->
<b>Question 1<br></b>
<input TYPE="radio" NAME="a" VALUE="1">answer choice 1<br>
<input TYPE="radio" NAME="a" VALUE="2">answer choice 2<br>
<input TYPE="radio" NAME="a" VALUE="3">answer chocie 3<br><br>
<b>Question 2<br></b>
<input TYPE="radio" NAME="b" VALUE="1">answer choice 1<br>
<input TYPE="radio" NAME="b" VALUE="2">answer choice 2<br>
<input TYPE="radio" NAME="b" VALUE="3">answer choice 3<br><br>
<b>Question 3<br></b>
<input TYPE="radio" NAME="c" VALUE="1">Answer choice 1<br>
<input TYPE="radio" NAME="c" VALUE="2">answer choice 2<br>
<input TYPE="radio" NAME="c" VALUE="3">answer choice 3<br><br>
<input id ="submit" type="submit" value="Get Result!" onclick="return process();"><br><br>
</form>
<script LANGUAGE="JavaScript">
function process()
{
var result1 = 0;
var result2 = 0;
var result3 = 0;
var f = document.f;
var i = 0;
<!--This is where the question values go-->
for (i = 0; i < f.a.length; i++) if (f.a[i].checked) value = f.a[i].value;
if (value == "1") { result1++; }
if (value == "2") { result2++; }
if (value == "3") { result3++; }
for (i = 0; i < f.b.length; i++) if (f.b[i].checked) value = f.b[i].value;
if (value == "1") { result1++; }
if (value == "2") { result2++; }
if (value == "3") { result3++; }
for (i = 0; i < f.c.length; i++) if (f.c[i].checked) value = f.c[i].value;
if (value == "1") { result1++; }
if (value == "2") { result2++; }
if (value == "3") { result3++; }
var out = "result1";
i = result1;
if (result2 > i) { out ="result2"; i = result2; }
if (result3 > i) { out ="result3"; i = result3; }
location.href = out + ".shtml";
}
function err(msg, url, line)
{
location.href = "error.html";
}
</SCRIPT>
</BODY>
</HTML>

How to calculate discount for price and clear form when radio button is changed

1) I am trying to calculate discount for price with this code but it does not work.
2) I want to clear form when the radio button is changed. Example the size is M and fill number in quantity input only If I change the size, the form will be clear or after amount show me If I change size, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function () {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if(s && q && m) {
if(q >= 1) {
if(s == 'S') {
result = s * q;
} else if(s == 'M') {
result = s * q;
} else if(s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result*5/100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').innerHTML = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
Your calculations are working as expected.
You have one problem in your Code:
document.getElementById('amount').innerHTML = result.toFixed(2); //Here with innerHTML
inputs cannot contain html. They can only contain a value. The property innerHTML is not ideal for input elements. What you are looking for is:
document.getElementById('amount').value = result.toFixed(2);
You must set the value of your amount, not innerHTML.
I have just edited your Snipped. Notice the changes I made on your code. A lot of stuff were unnecessary. Like your multiple if statements checking for 'S', 'M' ... Because at the end they all lead to the same calculation expression.
window.addEventListener("load", () => {
// clear then textboxes on Size change
document.querySelectorAll("input[name=size]").forEach(input=>{
input.addEventListener('change', ()=>{
clearTextBoxes();
});
});
});
var computeTotal = () =>
{
var s = document.querySelector('input[name=size]:checked').value;
var q = document.getElementById('qty').value;
var m = document.querySelector('input[name=member]:checked').value;
var result; //initialize to empty string
if(s && q && m && q >= 1) {
result = s * q;
result -= m === "YES" ? result*5/100 : 0;
}
// Change innerHTML to value
document.getElementById('amount').value = result == undefined ? " " : result.toFixed(2);
}
var clearTextBoxes = () => {
document.getElementById("qty").value = "";
document.getElementById("amount").value = "";
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="number" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate" onclick="computeTotal()">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
You need to clear the input fields when radio button changes. Find the working demo below
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function() {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if (s && q && m) {
if (q >= 1) {
if (s == 'S') {
result = s * q;
} else if (s == 'M') {
result = s * q;
} else if (s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result * 5 / 100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').value = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
// Add event listener to all radio items and add the clearfields logic
var memberRadios = document.querySelectorAll('input[type=radio][name="member"]');
var sizeRadios = document.querySelectorAll('input[type=radio][name="size"]');
Array.prototype.forEach.call(memberRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
Array.prototype.forEach.call(sizeRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
function clearFields(event) {
document.getElementById('qty').value = null;
document.getElementById('amount').value = null;
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>

Validate radio button in javascript

function validate()
{
var payment = checkRadio();
if (payment == false)
{
alert("Please select one button")
}
}
function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
else
{
return false;
}
}
}
The html code below creates the radio buttons for the client to select one of the payment methods
<P> Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
</P>
<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
My problem is that when I execute this code and run it on chrome nothing happens. If someone could spot out where about I went wrong I would really appreciate it.
You need to surround your html code with <form>
<form>
Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
</form>
And in your javascript change the checkRadio to:
function checkRadio()
{
var payment = document.getElementsByName('payment');
var paymentType = '';
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
console.log(payment[i].value)
paymentType = payment[i].value;
}
}
return paymentType != '' ? true : false;
}
JSFiddle: https://jsfiddle.net/ttgrk8xj/16/
In your code you are checking only the first element is checked because you are returning from function in first iteration.
function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
}
return false;
}

Limit the number of check-boxes allowed to be checked

function CountChecks(whichlist,forarray,maxchecked,latestcheck) {
// An array containing the id of each checkbox to monitor.
// List the id of each checkbox in the set. If more than
// one set, list other sets in their own arrays. The
// array name to use is passed to this function.
*// THIS PART IMPORTANT*//
var listone = new Array("1", "2", "3", "4", "5", "6");
*// THIS PART IMPORTANT*//
// End of customization.
var iterationlist;
eval("iterationlist="+whichlist);
var count = 0;
for( var i=0; i<iterationlist.length; i++ ) {
if( document.getElementById(iterationlist[i]).checked == true) { count++; }
if( count > maxchecked ) { latestcheck.checked = false; }
}
if( count > maxchecked ) {
alert('Sorry, only ' + maxchecked + ' may be checked.');
}
}
This is you can see CHECKBOX CHECK LIMITER.. And you can see works with function. I wanna do send this to js file from the page.. but Its not very functional becouse of array part. It has to create array's own by own.. I add the variable function part 'forarray'.. I dont know javascript and Im asking you it has to be like this when it create own arrays.
var {whichlist variable} = new Array({forarray variable list});
And HTML code like this.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','1',3,this)" value="2x2">2x2
<input id='2' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','2',3,this)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','3',3,this)" value="2x3">2x3
<input id='4' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','4',3,this)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','5',3,this)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','6',3,this)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','7',2,this)" value="red">Red
<input id='8' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','8',2,this)" value="gold">Gold
<input id='9' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','9',2,this)" value="green">Green
<input id='10' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','10',2,this)" value="silver">Silver
<input id='11' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','11',2,this)" value="blue">Blue
</p>
You do not need to do all of that. All you need to do is pass a reference to the element into the function and then use its name to query a list of its siblings. Count the number of checked boxes and prevent any others from being checked.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="listone" onclick="javascript:checkNumChecked(this, 3)"
value="2x2">2x2
<input id='2' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x3">2x3
<input id='4' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="red">Red
<input id='8' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="gold">Gold
<input id='9' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="green">Green
<input id='10' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="silver">Silver
<input id='11' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="blue">Blue
</p>
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
if (checked > limit) {
siblings[ct].checked = false
alert('Sorry, only ' + limit + ' item(s) may be checked.');
break;
}
}
}
</script>
However, alerts are annoying to end users. A much better way of doing this is to disable the other check boxes once the limit has been reached and re-enable them when a box is unchecked.
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>
To have the same, but make it work using only ids you can do the following:
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = [], checked = 0, item_num = parseInt(ele.id),
sct = (item_num < 7) ? 1 : 7, ect = (item_num < 7) ? 6 : 11;
for (ct = sct; ct <= ect; ct++) {
siblings.push(document.getElementById(ct));
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>

How to check to make sure a radio button is selected

I have a form that I need to figure out the code on how to make sure a radio button is selected
Here is the form
<body>
<div id="content">
<p>Enter the values below and click "Calculate".</p>
<label for="length">Length:</label>
<input type="text" id="length" /><br />
<label for="width">Width:</label>
<input type="text" id="width" /><br />
<label for="answer">Answer:</label>
<input type="text" id="Answer" disabled="disabled" /><br />
<input type="radio" name="Area" value="Area" check="checked"/>Area<br />
<input type="radio" name="Parimeter" value="Parimeter" />Parimeter<br />
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</body>
</html>
here is the code
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var length = parseFloat( $("length").value );
var width = parseFloat( $("width").value );
// $("area").value = "";
if (isNaN(length) || length <= 0) {
alert("Length must be a valid number\nand greater than zero.");
} else if(isNaN(width) || width <= 0) {
alert("Width must be a valid number\nand greater than zero.");
}
} else {
var area = width * length;
var perimeter = 2 * width + 2 * length;
$("area").value = area.toFixed(2);
$("perimeter").value = perimeter.toFixed(2);
}
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("length").focus();
}
Here are some links that may help you finish your homework:
http://www.w3schools.com/html/html_forms.asp
http://www.w3schools.com/jquery/default.asp
http://jsfiddle.net

Categories