Limit number of seat to be booked at a time - javascript

I have this simple table used for ticket reservation. It works fine but i want to improve it so a user can reserve 6 seats at a time if user need to add 7th seat should be alerted that he/she can book 6 seats at a time.
The other issue is how to make reserve button inactive if there is no any seat selected and make it active if one or more than one seats are selected?
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const hiddenSeatElem = document.getElementById("hidden-seats");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
} else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
hiddenSeatElem.value = result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100"><label for="A1">A1</label><br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> <label for="A2">A2</label><br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> <label for="A3">A3</label><br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"><label for="A4">A4</label><br>
<input type="checkbox" name="vehicle-b1" id="B1" value="100"><label for="B1">B1</label><br>
<input type="checkbox" name="vehicle-b2" id="B2" value="65"> <label for="B2">B2</label><br>
<input type="checkbox" name="vehicle-b3" id="B3" value="55"> <label for="B3">B3</label><br>
<input type="checkbox" name="vehicle-b4" id="B4" value="50"><label for="B4">B4</label><br>
<input type="checkbox" name="vehicle-c1" id="C1" value="100"><label for="C1">C1</label><br>
<input type="checkbox" name="vehicle-c2" id="C2" value="65"> <label for="C2">C2</label><br>
<input type="checkbox" name="vehicle-c3" id="C3" value="55"> <label for="C3">C3</label><br>
<input type="checkbox" name="vehicle-c4" id="C4" value="50"><label for="C4">C4</label><br>
<input type="hidden" name="total" id="hidden-total" value="0">
<input type="hidden" name="seats" id="hidden-seats" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span>
<!-- container for selected seats -->
<br> Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
</div>
</body>
</html>

I just added a small code chunk:
if(result.length>6){
e.preventDefault();
console.log("Alreday got 6! Event prevented... Alert the user here.");
//Remove the property added in selections in the code above.
delete selections[e.target.id];
return;
}
Where if the result array gets to more than 6 items, you prevent the checkbox from being checked, alert the user in some way (as you prefer) and exit the function with return.
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const hiddenSeatElem = document.getElementById("hidden-seats");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
} else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
// Enable the submit button if at least 1 checked
$(":submit").prop("disabled",!result.length>0);
if(result.length>6){
console.log("Alreday got 6! Event prevented... Alert the user here.");
e.preventDefault();
// Remove the property added in selections in the code above.
delete selections[e.target.id];
return;
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
hiddenSeatElem.value = result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100"><label for="A1">A1</label><br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> <label for="A2">A2</label><br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> <label for="A3">A3</label><br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"><label for="A4">A4</label><br>
<input type="checkbox" name="vehicle-b1" id="B1" value="100"><label for="B1">B1</label><br>
<input type="checkbox" name="vehicle-b2" id="B2" value="65"> <label for="B2">B2</label><br>
<input type="checkbox" name="vehicle-b3" id="B3" value="55"> <label for="B3">B3</label><br>
<input type="checkbox" name="vehicle-b4" id="B4" value="50"><label for="B4">B4</label><br>
<input type="checkbox" name="vehicle-c1" id="C1" value="100"><label for="C1">C1</label><br>
<input type="checkbox" name="vehicle-c2" id="C2" value="65"> <label for="C2">C2</label><br>
<input type="checkbox" name="vehicle-c3" id="C3" value="55"> <label for="C3">C3</label><br>
<input type="checkbox" name="vehicle-c4" id="C4" value="50"><label for="C4">C4</label><br>
<input type="hidden" name="total" id="hidden-total" value="0">
<input type="hidden" name="seats" id="hidden-seats" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span>
<!-- container for selected seats -->
<br> Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit" disabled>Reserve Now</button>
</p>
</form>
</div>
</body>
</html>
EDIT
To enable the submit button, I added this:
$(":submit").prop("disabled",!result.length>0);
It is disabled by defaut in the HTML markup.

without jquery
document.addEventListener("DOMContentLoaded", function() {
const selections = {};
const inputElems = document.querySelectorAll('input[type=checkbox]');
const reserveButton = document.getElementById('reserveButton');
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const hiddenSeatElem = document.getElementById("hidden-seats");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
inputElems[i].addEventListener("click", displayCheck);
}
function displayCheck(e) {
if (e.target.checked) {
if (Object.keys(selections).length >= 6) {
e.preventDefault();
alert('You can only reserve 6 seats at time');
return;
} else {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
} else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
result.length ? reserveButton.disabled = false : reserveButton.disabled = true;
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
hiddenSeatElem.value = result;
}
});
<html>
<head>
</head>
<body>
<div class="container">
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100"><label for="A1">A1</label><br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> <label for="A2">A2</label><br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> <label for="A3">A3</label><br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"><label for="A4">A4</label><br>
<input type="checkbox" name="vehicle-b1" id="B1" value="100"><label for="B1">B1</label><br>
<input type="checkbox" name="vehicle-b2" id="B2" value="65"> <label for="B2">B2</label><br>
<input type="checkbox" name="vehicle-b3" id="B3" value="55"> <label for="B3">B3</label><br>
<input type="checkbox" name="vehicle-b4" id="B4" value="50"><label for="B4">B4</label><br>
<input type="checkbox" name="vehicle-c1" id="C1" value="100"><label for="C1">C1</label><br>
<input type="checkbox" name="vehicle-c2" id="C2" value="65"> <label for="C2">C2</label><br>
<input type="checkbox" name="vehicle-c3" id="C3" value="55"> <label for="C3">C3</label><br>
<input type="checkbox" name="vehicle-c4" id="C4" value="50"><label for="C4">C4</label><br>
<input type="hidden" name="total" id="hidden-total" value="0">
<input type="hidden" name="seats" id="hidden-seats" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span>
<!-- container for selected seats -->
<br> Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit" id="reserveButton" disabled>Reserve Now</button>
</p>
</form>
</div>
</body>
</html>

You can check if selections contains more than 6 keys when e.target.checked is true.
To inactive/active the button, you can do this
reserveBtn.disabled = result.length == 0;
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const hiddenSeatElem = document.getElementById("hidden-seats");
const seatsElem = document.getElementById("selected-seats");
const reserveBtn = document.getElementById("reserve-button");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
if(Object.keys(selections).length>=6)
{
e.target.checked = false;
// alert goes here
// ...
return;
}
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
} else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
hiddenSeatElem.value = result;
reserveBtn.disabled = result.length == 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100"><label for="A1">A1</label><br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> <label for="A2">A2</label><br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> <label for="A3">A3</label><br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"><label for="A4">A4</label><br>
<input type="checkbox" name="vehicle-b1" id="B1" value="100"><label for="B1">B1</label><br>
<input type="checkbox" name="vehicle-b2" id="B2" value="65"> <label for="B2">B2</label><br>
<input type="checkbox" name="vehicle-b3" id="B3" value="55"> <label for="B3">B3</label><br>
<input type="checkbox" name="vehicle-b4" id="B4" value="50"><label for="B4">B4</label><br>
<input type="checkbox" name="vehicle-c1" id="C1" value="100"><label for="C1">C1</label><br>
<input type="checkbox" name="vehicle-c2" id="C2" value="65"> <label for="C2">C2</label><br>
<input type="checkbox" name="vehicle-c3" id="C3" value="55"> <label for="C3">C3</label><br>
<input type="checkbox" name="vehicle-c4" id="C4" value="50"><label for="C4">C4</label><br>
<input type="hidden" name="total" id="hidden-total" value="0">
<input type="hidden" name="seats" id="hidden-seats" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span>
<!-- container for selected seats -->
<br> Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit" id="reserve-button" disabled>Reserve Now</button>
</p>
</form>
</div>
</body>
</html>

Related

Why do I get this reference error for an undefined variable when I run this js function

Here is my HTML:
<head>
<link rel="stylesheet" href="form.css">
<script type="text/javascript" src="form.js"></script>
</head>
<body>
<div id="wrapper">
<center>
<h1 hidden id="result">If you are traveling in <span class="input" id="countryt">(ctry)</span> and find yourself having to cross a piranha-filled river, here's how to do it <span class="input" id="adverbGroup1t">(adv1)</span>: Pirahnas are more <span class="input" id="adjectiveGroup1t">(adj1)</span> during the day, so cross the river at night. Avoid areas with netted <span class="input" id="animalt">(anml)</span> traps, piranhas may be <span class="input" id="verbGroup1t">(vrb1)</span> there looking to <span class="input" id="verbGroup2t">(vrb2)</span> you! When <span class="input" id="verbGroup3t"></span>(vrb3) the river, swim <span class="input" id="adverbGroup2t">(adv2)</span>. You don't want to wake them up and make them <span class="input" id="adjectiveGroup2t">(adj2)</span>! Whatever you do, if you have an open wound, try to find another way to get back to <span class="input" id="country2t">(ctry2)</span>. Pirahnas are attracted to fresh <span class="input" id="liquidt">(lqd)</span> and will most likely take a bite out of your <span class="input" id="bodyPartt">(bp)</span> if you <span class="input" id="verbGroup4t">(vrb4)</span> the water!</h1>
<h1 id="headText">Fill In The Form</h1>
<!-- <form action="form.php" method="post"> -->
<div id="form-elements"></div>
<form onsubmit="submitted()" id="form">
<p>A Country:</p>
<input autocomplete="off" type="text" name="country2Input" id="country">
<p>=============================</p>
<p>An Adverb:</p>
<input type="radio" value="awfully" id="awfully" name="adverbGroup1">
<label for="awfully">awfully</label>
<input type="radio" value="slowly" id="slowly" name="adverbGroup1">
<label for="slowly">slowly</label>
<input type="radio" value="clumsily" id="clumsily" name="adverbGroup1">
<label for="clumsily">clumsily</label>
<p>=============================</p>
<p>An Adjective:</p>
<input type="radio" value="amused" id="amused" name="adjectiveGroup1">
<label for="amused">amused</label>
<input type="radio" value="adventerous" id="adventerous" name="adjectiveGroup1">
<label for="adventerous">adventerous</label>
<input type="radio" value="little" id="little" name="adjectiveGroup1">
<label for="little">little</label>
<p>=============================</p>
<p>An Animal:</p>
<input autocomplete="off" type="text"name="animalInput" id="animal">
<p>=============================</p>
<p>A Verb:</p>
<input type="radio" value="running" value="" id="running" name="verbGroup1">
<label for="running">running</label>
<input type="radio" value="dancing" value="" id="dancing" name="verbGroup1">
<label for="dancing">dancing</label>
<input type="radio" value="thinking" value="" id="thinking" name="verbGroup1">
<label for="thinking">thinking</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="leave" value="" id="leave" name="verbGroup2">
<label for="leave">leave</label>
<input type="radio" value="bend" value="" id="bend" name="verbGroup2">
<label for="bend">bend</label>
<input type="radio" value="watch" value="" id="watch" name="verbGroup2">
<label for="watch">watch</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="capturing" id="capturing" name="verbGroup3">
<label for="capturing">capturing</label>
<input type="radio" value="drinking" id="drinking" name="verbGroup3">
<label for="drinking">drinking</label>
<input type="radio" value="creating" id="creating" name="verbGroup3">
<label for="creating">creating</label>
<p>=============================</p>
<p>Another Adverb:</p>
<input type="radio" value="carelessly" id="carelessly" name="adverbGroup2">
<label for="carelessly">carelessly</label>
<input type="radio" value="rapidly" id="rapidly" name="adverbGroup2">
<label for="rapidly">rapidly</label>
<input type="radio" value="greedily" id="greedily" name="adverbGroup2">
<label for="greedily">greedily</label>
<p>=============================</p>
<p>Another Adjective:</p>
<input type="radio" value="invisible" id="invisible" name="adjectiveGroup2">
<label for="invisible">invisible</label>
<input type="radio" value="insane" id="insane" name="adjectiveGroup2">
<label for="insane">insane</label>
<input type="radio" value="confused" id="confused" name="adjectiveGroup2">
<label for="confused">confused</label>
<p>=============================</p>
<p>Another Country:</p>
<input autocomplete="off" type="text" name="countryInput" id="country2">
<p>=============================</p>
<p>A type of liquid:</p>
<input type="radio" value="gasoline" id="gasoline" name="liquid">
<label for="gasoline">gasoline</label>
<input type="radio" value="water" id="water" name="liquid">
<label for="water">water</label>
<input type="radio" value="coffee" id="coffee" name="liquid">
<label for="coffee">coffee</label>
<p>=============================</p>
<p>Body Part:</p>
<input type="radio" value="toes" id="toes" name="bodyPart">
<label for="toes">toes</label>
<input type="radio" value="fingers" id="fingers" name="bodyPart">
<label for="fingers">fingers</label>
<input type="radio" value="face" id="face" name="bodyPart">
<label for="face">face</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="clean" id="clean" name="verbGroup4">
<label for="clean">clean</label>
<input type="radio" value="watch" id="watch2" name="verbGroup4">
<label for="watch2">watch</label>
<input type="radio" value="escape" id="escape" name="verbGroup4">
<label for="escape">escape</label>
<br>
<br>
</form>
<button onclick="submitted()" id="sub" >Submit</button>
<button hidden onclick="show()" id="show">Show result</button>
</div>
</center>
</div>
</body>
</html>
And here is my JS
function submitted() {
const btn = document.querySelector('#sub');
btn.addEventListener("click", () => {
var countryvalue = document.getElementById("country").value
console.log(countryvalue)
//divider
const adverbGroup1s = document.querySelectorAll('input[name="adverbGroup1"]');
let adverbGroup1value;
for (const adverbGroup1 of adverbGroup1s) {
if (adverbGroup1.checked) {
adverbGroup1value = adverbGroup1.value;
console.log(adverbGroup1value)
break;
}
}
//divider
const adjectiveGroup1s = document.querySelectorAll('input[name="adjectiveGroup1"]');
let adjectiveGroup1value;
for (const adjectiveGroup1 of adjectiveGroup1s) {
if (adjectiveGroup1.checked) {
adjectiveGroup1value = adjectiveGroup1.value;
console.log(adjectiveGroup1value)
break;
}
}
//divider
var animalvalue = document.getElementById("animal").value
console.log(animalvalue)
//divider
const verbGroup1s = document.querySelectorAll('input[name="verbGroup1"]');
let verbGroup1value;
for (const verbGroup1 of verbGroup1s) {
if (verbGroup1.checked) {
verbGroup1value = verbGroup1.value;
console.log(verbGroup1value)
break;
}
}
//divider
const verbGroup2s = document.querySelectorAll('input[name="verbGroup2"]');
let verbGroup2value;
for (const verbGroup2 of verbGroup2s) {
if (verbGroup2.checked) {
verbGroup2value = verbGroup2.value;
console.log(verbGroup2value)
break;
}
}
//divider
const verbGroup3s = document.querySelectorAll('input[name="verbGroup3"]');
let verbGroup3value;
for (const verbGroup3 of verbGroup3s) {
if (verbGroup3.checked) {
verbGroup3value = verbGroup3.value;
console.log(verbGroup3value)
break;
}
}
//divider
const adverbGroup2s = document.querySelectorAll('input[name="adverbGroup2"]');
let adverbGroup2value;
for (const adverbGroup2 of adverbGroup2s) {
if (adverbGroup2.checked) {
adverbGroup2value = adverbGroup2.value;
console.log(adverbGroup2value)
break;
}
}
//divider
const adjectiveGroup2s = document.querySelectorAll('input[name="adjectiveGroup2"]');
let adjectiveGroup2value;
for (const adjectiveGroup2 of adjectiveGroup2s) {
if (adjectiveGroup2.checked) {
adjectiveGroup2value = adjectiveGroup2.value;
console.log(adjectiveGroup2value)
break;
}
}
//divider
var country2value = document.getElementById("country2").value
console.log(country2value)
//divider
const liquids = document.querySelectorAll('input[name="liquid"]');
let liquidvalue;
for (const liquid of liquids) {
if (liquid.checked) {
liquidvalue = liquid.value;
console.log(liquidvalue)
break;
}
}
//divider
const bodyParts = document.querySelectorAll('input[name="bodyPart"]');
let bodyPartvalue;
for (const bodyPart of bodyParts) {
if (bodyPart.checked) {
bodyPartvalue = bodyPart.value;
console.log(bodyPartvalue)
break;
}
}
//divider
const verbGroup4s = document.querySelectorAll('input[name="verbGroup4"]');
let verbGroup4value;
for (const verbGroup4 of verbGroup4s) {
if (verbGroup4.checked) {
verbGroup4value = verbGroup4.value;
console.log(verbGroup4value)
break;
}
}
document.getElementById("form").reset();
document.getElementById("show").hidden = false
});
}
function show() {
document.getElementById("form").hidden = true
document.getElementById("sub").hidden = true
document.getElementById("show").hidden = true
document.getElementById("headText").hidden = true
document.getElementById("result").hidden = false
document.getElementById("countryt").innerHTML = countryvalue
document.getElementById("adverbGroup1t").innerHTML = adverbGroup1value
document.getElementById("adjectiveGroup1t").innerHTML = adjectiveGroup1value
document.getElementById("animalt").innerHTML = animalvalue
document.getElementById("verbGroup1t").innerHTML = verbGroup1value
document.getElementById("verbGroup2t").innerHTML = verbGroup2value
document.getElementById("verbGroup3t").innerHTML = verbGroup3value
document.getElementById("adverbGroup2t").innerHTML = adverbGroup2value
document.getElementById("adjectiveGroup2t").innerHTML = adjectiveGroup2value
document.getElementById("country2t").innerHTML = country2value
document.getElementById("liquidt").innerHTML = liquidvalue
document.getElementById("bodyPartt").innerHTML = bodyPartvalue
document.getElementById("verbGroup4t").innerHTML = verbGroup4value
}
When I run this, I expect all of the content inside each span tag to be replaced with its correct strings which are stored in the variables which end with "value"
However, whenever I run this, I get this error:
"Uncaught ReferenceError: countryvalue is not defined at show (form.js:174:53) at HTMLButtonElement.onclick ((index):110:47)"
How do I make this work as I explained earlier
hi bro
You should put your script file at the end of the html file and make sure that the file address is correct.
function submitted() {
const btn = document.querySelector('#sub');
btn.addEventListener("click", () => {
var countryvalue = document.getElementById("country").value
console.log(countryvalue)
//divider
const adverbGroup1s = document.querySelectorAll('input[name="adverbGroup1"]');
let adverbGroup1value;
for (const adverbGroup1 of adverbGroup1s) {
if (adverbGroup1.checked) {
adverbGroup1value = adverbGroup1.value;
console.log(adverbGroup1value)
break;
}
}
//divider
const adjectiveGroup1s = document.querySelectorAll('input[name="adjectiveGroup1"]');
let adjectiveGroup1value;
for (const adjectiveGroup1 of adjectiveGroup1s) {
if (adjectiveGroup1.checked) {
adjectiveGroup1value = adjectiveGroup1.value;
console.log(adjectiveGroup1value)
break;
}
}
//divider
var animalvalue = document.getElementById("animal").value
console.log(animalvalue)
//divider
const verbGroup1s = document.querySelectorAll('input[name="verbGroup1"]');
let verbGroup1value;
for (const verbGroup1 of verbGroup1s) {
if (verbGroup1.checked) {
verbGroup1value = verbGroup1.value;
console.log(verbGroup1value)
break;
}
}
//divider
const verbGroup2s = document.querySelectorAll('input[name="verbGroup2"]');
let verbGroup2value;
for (const verbGroup2 of verbGroup2s) {
if (verbGroup2.checked) {
verbGroup2value = verbGroup2.value;
console.log(verbGroup2value)
break;
}
}
//divider
const verbGroup3s = document.querySelectorAll('input[name="verbGroup3"]');
let verbGroup3value;
for (const verbGroup3 of verbGroup3s) {
if (verbGroup3.checked) {
verbGroup3value = verbGroup3.value;
console.log(verbGroup3value)
break;
}
}
//divider
const adverbGroup2s = document.querySelectorAll('input[name="adverbGroup2"]');
let adverbGroup2value;
for (const adverbGroup2 of adverbGroup2s) {
if (adverbGroup2.checked) {
adverbGroup2value = adverbGroup2.value;
console.log(adverbGroup2value)
break;
}
}
//divider
const adjectiveGroup2s = document.querySelectorAll('input[name="adjectiveGroup2"]');
let adjectiveGroup2value;
for (const adjectiveGroup2 of adjectiveGroup2s) {
if (adjectiveGroup2.checked) {
adjectiveGroup2value = adjectiveGroup2.value;
console.log(adjectiveGroup2value)
break;
}
}
//divider
var country2value = document.getElementById("country2").value
console.log(country2value)
//divider
const liquids = document.querySelectorAll('input[name="liquid"]');
let liquidvalue;
for (const liquid of liquids) {
if (liquid.checked) {
liquidvalue = liquid.value;
console.log(liquidvalue)
break;
}
}
//divider
const bodyParts = document.querySelectorAll('input[name="bodyPart"]');
let bodyPartvalue;
for (const bodyPart of bodyParts) {
if (bodyPart.checked) {
bodyPartvalue = bodyPart.value;
console.log(bodyPartvalue)
break;
}
}
//divider
const verbGroup4s = document.querySelectorAll('input[name="verbGroup4"]');
let verbGroup4value;
for (const verbGroup4 of verbGroup4s) {
if (verbGroup4.checked) {
verbGroup4value = verbGroup4.value;
console.log(verbGroup4value)
break;
}
}
document.getElementById("form").reset();
document.getElementById("show").hidden = false
});
}
function show() {
document.getElementById("form").hidden = true
document.getElementById("sub").hidden = true
document.getElementById("show").hidden = true
document.getElementById("headText").hidden = true
document.getElementById("result").hidden = false
document.getElementById("countryt").innerHTML = countryvalue
document.getElementById("adverbGroup1t").innerHTML = adverbGroup1value
document.getElementById("adjectiveGroup1t").innerHTML = adjectiveGroup1value
document.getElementById("animalt").innerHTML = animalvalue
document.getElementById("verbGroup1t").innerHTML = verbGroup1value
document.getElementById("verbGroup2t").innerHTML = verbGroup2value
document.getElementById("verbGroup3t").innerHTML = verbGroup3value
document.getElementById("adverbGroup2t").innerHTML = adverbGroup2value
document.getElementById("adjectiveGroup2t").innerHTML = adjectiveGroup2value
document.getElementById("country2t").innerHTML = country2value
document.getElementById("liquidt").innerHTML = liquidvalue
document.getElementById("bodyPartt").innerHTML = bodyPartvalue
document.getElementById("verbGroup4t").innerHTML = verbGroup4value
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="form.css">
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="wrapper">
<center>
<h1 hidden id="result">If you are traveling in <span class="input" id="countryt">(ctry)</span> and find yourself having to cross a piranha-filled river, here's how to do it <span class="input" id="adverbGroup1t">(adv1)</span>: Pirahnas are more <span class="input" id="adjectiveGroup1t">(adj1)</span> during the day, so cross the river at night. Avoid areas with netted <span class="input" id="animalt">(anml)</span> traps, piranhas may be <span class="input" id="verbGroup1t">(vrb1)</span> there looking to <span class="input" id="verbGroup2t">(vrb2)</span> you! When <span class="input" id="verbGroup3t"></span>(vrb3) the river, swim <span class="input" id="adverbGroup2t">(adv2)</span>. You don't want to wake them up and make them <span class="input" id="adjectiveGroup2t">(adj2)</span>! Whatever you do, if you have an open wound, try to find another way to get back to <span class="input" id="country2t">(ctry2)</span>. Pirahnas are attracted to fresh <span class="input" id="liquidt">(lqd)</span> and will most likely take a bite out of your <span class="input" id="bodyPartt">(bp)</span> if you <span class="input" id="verbGroup4t">(vrb4)</span> the water!</h1>
<h1 id="headText">Fill In The Form</h1>
<!-- <form action="form.php" method="post"> -->
<div id="form-elements"></div>
<form onsubmit="submitted()" id="form">
<p>A Country:</p>
<input autocomplete="off" type="text" name="country2Input" id="country">
<p>=============================</p>
<p>An Adverb:</p>
<input type="radio" value="awfully" id="awfully" name="adverbGroup1">
<label for="awfully">awfully</label>
<input type="radio" value="slowly" id="slowly" name="adverbGroup1">
<label for="slowly">slowly</label>
<input type="radio" value="clumsily" id="clumsily" name="adverbGroup1">
<label for="clumsily">clumsily</label>
<p>=============================</p>
<p>An Adjective:</p>
<input type="radio" value="amused" id="amused" name="adjectiveGroup1">
<label for="amused">amused</label>
<input type="radio" value="adventerous" id="adventerous" name="adjectiveGroup1">
<label for="adventerous">adventerous</label>
<input type="radio" value="little" id="little" name="adjectiveGroup1">
<label for="little">little</label>
<p>=============================</p>
<p>An Animal:</p>
<input autocomplete="off" type="text"name="animalInput" id="animal">
<p>=============================</p>
<p>A Verb:</p>
<input type="radio" value="running" value="" id="running" name="verbGroup1">
<label for="running">running</label>
<input type="radio" value="dancing" value="" id="dancing" name="verbGroup1">
<label for="dancing">dancing</label>
<input type="radio" value="thinking" value="" id="thinking" name="verbGroup1">
<label for="thinking">thinking</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="leave" value="" id="leave" name="verbGroup2">
<label for="leave">leave</label>
<input type="radio" value="bend" value="" id="bend" name="verbGroup2">
<label for="bend">bend</label>
<input type="radio" value="watch" value="" id="watch" name="verbGroup2">
<label for="watch">watch</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="capturing" id="capturing" name="verbGroup3">
<label for="capturing">capturing</label>
<input type="radio" value="drinking" id="drinking" name="verbGroup3">
<label for="drinking">drinking</label>
<input type="radio" value="creating" id="creating" name="verbGroup3">
<label for="creating">creating</label>
<p>=============================</p>
<p>Another Adverb:</p>
<input type="radio" value="carelessly" id="carelessly" name="adverbGroup2">
<label for="carelessly">carelessly</label>
<input type="radio" value="rapidly" id="rapidly" name="adverbGroup2">
<label for="rapidly">rapidly</label>
<input type="radio" value="greedily" id="greedily" name="adverbGroup2">
<label for="greedily">greedily</label>
<p>=============================</p>
<p>Another Adjective:</p>
<input type="radio" value="invisible" id="invisible" name="adjectiveGroup2">
<label for="invisible">invisible</label>
<input type="radio" value="insane" id="insane" name="adjectiveGroup2">
<label for="insane">insane</label>
<input type="radio" value="confused" id="confused" name="adjectiveGroup2">
<label for="confused">confused</label>
<p>=============================</p>
<p>Another Country:</p>
<input autocomplete="off" type="text" name="countryInput" id="country2">
<p>=============================</p>
<p>A type of liquid:</p>
<input type="radio" value="gasoline" id="gasoline" name="liquid">
<label for="gasoline">gasoline</label>
<input type="radio" value="water" id="water" name="liquid">
<label for="water">water</label>
<input type="radio" value="coffee" id="coffee" name="liquid">
<label for="coffee">coffee</label>
<p>=============================</p>
<p>Body Part:</p>
<input type="radio" value="toes" id="toes" name="bodyPart">
<label for="toes">toes</label>
<input type="radio" value="fingers" id="fingers" name="bodyPart">
<label for="fingers">fingers</label>
<input type="radio" value="face" id="face" name="bodyPart">
<label for="face">face</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="clean" id="clean" name="verbGroup4">
<label for="clean">clean</label>
<input type="radio" value="watch" id="watch2" name="verbGroup4">
<label for="watch2">watch</label>
<input type="radio" value="escape" id="escape" name="verbGroup4">
<label for="escape">escape</label>
<br>
<br>
</form>
<button onclick="submitted()" id="sub" >Submit</button>
<button hidden onclick="show()" id="show">Show result</button>
</div>
</center>
</div>
</body>
</html>
</html>
Check the address of this file
<script type="text/javascript" src="app.js"></script>
A few recommendations:
First, to avoid clicking twice on submit button, remove an additional subscription from the submitted function.
So, basically you can remove these lines, from submitted:
const btn = document.querySelector('#sub');
btn.addEventListener("click", () => {
Second, to avoid countryvalue is not defined errors you need to declare your variables out of the submitted function scope, so the variables are visible both in submitte and in show
For example:
let countryvalue;
function submitted() {
countryvalue = document.getElementById("country").value;
}
function show() {
document.getElementById("countryt").innerHTML = countryvalue;
}

how to add value from range input to total amount?

I managed to summarize the values from the radio buttons, but I just can’t add the values from range inputs, how can this be implemented??
And yet, since the slider on the two range inputs initially has a value of 1, then in Sum: should already be 2.
$(document).ready(function() {
$(".in_objem").on('input', function() {
$(".range-indicator").text($(this).val());
});
$(".in_nagrev").on('input', function() {
$(".nagrev-indicator").text($(this).val());
});
// $(".in_objem").on('input', function() {
// var elem= parseInt($(this).val());
// });
$(".premium-inpts").on('click', function(){
var sum = 0;
$('.premium-inpts').each(function(){
if ($(this).is(':checked')){
sum = sum + parseInt($(this).next('.flexy-block').attr("price"));
}
});
console.log(sum);
$("#price-board").text(sum);
$("#output-price").val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<span class="nagrev-indicator">1</span><span>units1</span>
</div>
<div>
<input class="in_nagrev" name="productivity1" type="range" min="1" max="30" value="1">
</div>
</div>
<div>
<div>
<span class="range-indicator">1</span><span>units2</span>
</div>
<div>
<input class="in_objem" name="productivity2" type="range" min="1" max="30" value="1">
</div>
</div>
<div>
<input class="premium-inpts" id="a" type="radio" value="work">
<label class="flexy-block" for="a" price="300">
<span>Work</span>
</label>
<input class="premium-inpts" id="b" type="radio" value="chill">
<label class="flexy-block" for="b" price="20">
<span>Chill</span>
</label>
</div>
<div class="motors-container">
<input class="premium-inpts" id="c" type="radio" value="Automatic">
<label class="flexy-block" for="c" price="90">
<span>Automatic</span>
</label>
<input class="premium-inpts" id="d" type="radio" value="Common">
<label class="flexy-block" for="d" price="0">
<span>Common</span>
</label>
</div>
<div class="price-board">Sum: <span id="price-board"></span></div>
<input id="output-price" name="Sum" type="hidden" value="">
Perhaps this is done somehow through an array, but I am not very good at js, so do not judge strictly.
You can sum the value of all the checked radio buttons with the slider value on the input event:
$(".in_objem,.in_nagrev").on('input', function() {
var elem = 0;
//sum the slider value
$(".in_objem,.in_nagrev").each(function(){
elem += Number($(this).val());
});
var v = 0;
//sum the checked radio buttons
$('.premium-inpts:checked').each(function(){
v = v + parseInt($(this).next('.flexy-block').attr("price"));
});
$("#price-board").text(v + elem);
$("#output-price").val(v + elem);
});
$(".in_objem,.in_nagrev").trigger('input'); // trigger the event to show the sum on page load
Working Code Example:
$(document).ready(function() {
$(".in_objem").on('input', function() {
$(".range-indicator").text($(this).val());
});
$(".in_nagrev").on('input', function() {
$(".nagrev-indicator").text($(this).val());
});
$(".in_objem,.in_nagrev").on('input', function() {
var elem = 0;
$(".in_objem,.in_nagrev").each(function(){
elem += Number($(this).val());
});
var v = 0;
$('.premium-inpts:checked').each(function(){
v = v + parseInt($(this).next('.flexy-block').attr("price"));
});
$("#price-board").text(v + elem);
$("#output-price").val(v + elem);
});
$(".in_objem,.in_nagrev").trigger('input');
$(".premium-inpts").on('click', function(){
var sum = 0;
var n1 = Number($('.in_objem').val());
var n2 = Number($('.in_nagrev').val());
sum = n1+n2;
$('.premium-inpts:checked').each(function(){
sum = sum + parseInt($(this).next('.flexy-block').attr("price"));
});
//console.log(sum);
$("#price-board").text(sum);
$("#output-price").val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<span class="nagrev-indicator">1</span><span>units1</span>
</div>
<div>
<input class="in_nagrev" name="productivity1" type="range" min="1" max="30" value="1">
</div>
</div>
<div>
<div>
<span class="range-indicator">1</span><span>units2</span>
</div>
<div>
<input class="in_objem" name="productivity2" type="range" min="1" max="30" value="1">
</div>
</div>
<div>
<input class="premium-inpts" id="a" type="radio" value="work"> //this is value for form
<label class="flexy-block" for="a" price="300">
<span>Work</span>
</label>
<input class="premium-inpts" id="b" type="radio" value="chill">
<label class="flexy-block" for="b" price="20">
<span>Chill</span>
</label>
</div>
<div class="motors-container">
<input class="premium-inpts" id="c" type="radio" value="Automatic"> //this is value for form
<label class="flexy-block" for="c" price="90">
<span>Automatic</span>
</label>
<input class="premium-inpts" id="d" type="radio" value="Common">
<label class="flexy-block" for="d" price="0">
<span>Common</span>
</label>
</div>
<div class="price-board">Sum: <span id="price-board"></span></div>
<input id="output-price" name="Sum" type="hidden" value="">
You need to get the value of the range objects and parse them to numbers and add them in your sum:
$(document).ready(function() {
$(".in_objem").on('input', function() {
$(".range-indicator").text($(this).val());
});
$(".in_nagrev").on('input', function() {
$(".nagrev-indicator").text($(this).val());
});
//$(".in_objem").on('input', function() {
// var elem= parseInt($(this).val());
//});
$(".premium-inpts").on('click', function(){
var sum = 0;
$('.premium-inpts').each(function(){
if ($(this).is(':checked')){
sum = sum + parseInt($(this).next('.flexy-block').attr("price")) + parseInt($(".in_objem").val(),10)+ parseInt($(".in_objem").val(),10) ;
}
});
console.log(sum);
$("#price-board").text(sum);
$("#output-price").val(sum);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<span class="nagrev-indicator">1</span><span>units1</span>
</div>
<div>
<input class="in_nagrev" name="productivity1" type="range" min="1" max="30" value="1">
</div>
</div>
<div>
<div>
<span class="range-indicator">1</span><span>units2</span>
</div>
<div>
<input class="in_objem" name="productivity2" type="range" min="1" max="30" value="1">
</div>
</div>
<div>
<input class="premium-inpts" id="a" type="radio" value="work"> //this is value for form
<label class="flexy-block" for="a" price="300">
<span>Work</span>
</label>
<input class="premium-inpts" id="b" type="radio" value="chill">
<label class="flexy-block" for="b" price="20">
<span>Chill</span>
</label>
</div>
<div class="motors-container">
<input class="premium-inpts" id="c" type="radio" value="Automatic"> //this is value for form
<label class="flexy-block" for="c" price="90">
<span>Automatic</span>
</label>
<input class="premium-inpts" id="d" type="radio" value="Common">
<label class="flexy-block" for="d" price="0">
<span>Common</span>
</label>
</div>
<div class="price-board">Sum: <span id="price-board"></span></div>
<input id="output-price" name="Sum" type="hidden" value="">
As mentioned by aprouja1, you need to get their values. An easy way to do this, is by giving both range sliders an ID in HTML.(For Example slider1 & slider2).
Then use document.getElementById("slider1").value & document.getElementById("slider2").value to get their values. You can save these to a variable and calculate the sum this way.
let slider1Value = document.getElementById("slider1").value;
let slider2Value = document.getElementById("slider2").value;
sum = slider1Value + slider2Value;

How to show an alert box output and inside the function also have the calculation

I want when the user click button Submit Order, the alert box contain words and also total price of the selected size and topping appear , then have a button ok so it will close the alert button.I need to use JavaScript to calculate the total price of the pizza if the user select the radio button and checkbox. But I don't really know how to do it. Can anyone help me . Btw for this problem I only use JavaScript and html only
This is some codes that I've already progress on using html and javascript
<form>
<p><b>Step 2 : Select the size of pizza you want:</b></p>
<input type="radio" name="size" value="small" id="radOne">Small
<input type="radio" name="size" value="medium" id="radTwo">Medium
<input type="radio" name="size" value="large" id="radThree">Large
<br>
<p><b>Step 3 : Select the pizza toppings you want:</b></p>
<input type="checkbox" name="topping" value="peperoni">Pepperoni
<input type="checkbox" name="topping" value="Sausage">Sausage
<input type="checkbox" name="topping" value="Mushrooms">Mushrooms<br>
<input type="checkbox" name="topping" value="Pineapple">Pineapple
<input type="checkbox" name="topping" value="Black Olives">Black Olives
<input type="checkbox" name="topping" value="Meatball">Meatball <br>
<br>
<input type="button" onclick="submit()" value="Submit Order">
<input type="button" onclick="reset()" value="Clear Entries">
</form>
<script>
function submit() {
document.getElementById("frm1").submit();
var radOne = document.getElementById("radOne");
var radTwo = document.getElementById("radTwo");
var radThree = document.getElementById("radThree");
var price;
if (radOne.checked){
price = 15.00;}
else if (radTwo.checked){
price = 20.00;}
else
price = 25.00;
{alert("MY PIZZA CAFE");}
}
function reset() {
document.getElementById("frm1").reset();
}
</script>
Somebody has answered your question. But here is my solution. You can refer to it.
Hope to help, my friend :))
https://jsfiddle.net/ga7ptu5o/
<form id="frm1">
<p><b>Step 2 : Select the size of pizza you want:</b></p>
<input type="radio" name="size" value="small" id="radOne">Small
<input type="radio" name="size" value="medium" id="radTwo">Medium
<input type="radio" name="size" value="large" id="radThree">Large
<br>
<p><b>Step 3 : Select the pizza toppings you want:</b></p>
<input type="checkbox" name="topping" value="peperoni">Pepperoni
<input type="checkbox" name="topping" value="Sausage">Sausage
<input type="checkbox" name="topping" value="Mushrooms">Mushrooms<br>
<input type="checkbox" name="topping" value="Pineapple">Pineapple
<input type="checkbox" name="topping" value="Black Olives">Black Olives
<input type="checkbox" name="topping" value="Meatball">Meatball <br>
<br>
<input type="button" onclick="submitFunc()" value="Submit Order">
<input type="button" onclick="reset()" value="Clear Entries">
</form>
function submitFunc(){
//document.getElementById("frm1").submit();
var form = document.getElementById('frm1');
var price = 0;
var size_value;
var checked_size = document.querySelector('input[name = "size"]:checked');
var checked_topping = form.querySelectorAll('input[type = "checkbox"]');
if(checked_size != null){
size_value = checked_size.value;
if(size_value === 'small'){
price = 15.00;
}else if (size_value === 'medium'){
price = 20.00;
}else{
price = 25.00;
}
} else {
alert('You have to select a Pizza size');
return;
}
var txt_topping = "";
var i;
for(i = 0; i < checked_topping.length; i++){
if(checked_topping[i].checked){
txt_topping = txt_topping + checked_topping[i].value + ", ";
}
}
if(txt_topping != '')
txt_topping = '. With ' + txt_topping + ' topping';
alert('You have selected ' + size_value + ' size, price is: ' + price + txt_topping);
};
function reset() {
document.getElementById("frm1").reset();
};
You're on the correct path, it's just that submit() function triggers the form submit which does a redirect. Check the code below for sausage and pepperoni and do the same for the other checkboxes.
function calculate(e) {
var radOne = document.getElementById("radOne");
var radTwo = document.getElementById("radTwo");
var radThree = document.getElementById("radThree");
var pepperoni = document.getElementById("pepperoni");
var sausage = document.getElementById("sausage");
var price;
if (radOne.checked) {
price = 15.00;
alert("Small checked");
}
if (radTwo.checked) {
price = 20.00;
alert("Medium checked");
}
if (radThree.checked) {
price = 25.00;
}
if (pepperoni.checked) {
alert("Pepperoni checked");
price += 1.5;
}
if (sausage.checked) {
alert("Sausage checked");
price += 2;
}
if (confirm("Your Pizza is " + "Total Price is " + price)) {
alert("Ok");
} else {
alert("Cancelled");
}
}
function reset(e) {
document.getElementById("frm1").reset();
}
<html>
<body>
<form>
<p><b>Step 2 : Select the size of pizza you want:</b></p>
<input type="radio" name="size" value="small" id="radOne">Small
<input type="radio" name="size" value="medium" id="radTwo">Medium
<input type="radio" name="size" value="large" id="radThree">Large
<br>
<p><b>Step 3 : Select the pizza toppings you want:</b></p>
<input id="pepperoni" type="checkbox" name="topping" value="peperoni">Pepperoni
<input id="sausage" type="checkbox" name="topping" value="Sausage">Sausage
<input type="checkbox" name="topping" value="Mushrooms">Mushrooms<br>
<input type="checkbox" name="topping" value="Pineapple">Pineapple
<input type="checkbox" name="topping" value="Black Olives">Black Olives
<input type="checkbox" name="topping" value="Meatball">Meatball <br>
<br>
<input type="button" onclick="calculate(this)" value="Submit" />
<input type="button" onclick="reset(this)" value="Clear Entries" />
</form>
</body>
</html>
<form>
<p><b>Step 2 : Select the size of pizza you want:</b></p>
<input type="radio" name="size" value="small" id="radOne">Small
<input type="radio" name="size" value="medium" id="radTwo">Medium
<input type="radio" name="size" value="large" id="radThree">Large
<br>
<p><b>Step 3 : Select the pizza toppings you want:</b></p>
<input type="checkbox" name="topping" value="peperoni">Pepperoni
<input type="checkbox" name="topping" value="Sausage">Sausage
<input type="checkbox" name="topping" value="Mushrooms">Mushrooms<br>
<input type="checkbox" name="topping" value="Pineapple">Pineapple
<input type="checkbox" name="topping" value="Black Olives">Black Olives
<input type="checkbox" name="topping" value="Meatball">Meatball <br>
<br>
<input type="button" onclick="submitFX()" value="Submit Order">
<input type="button" onclick="reset()" value="Clear Entries">
</form>
<script>
function submitFX() {
// document.getElementById("frm1").submit();
var radOne = document.getElementById("radOne");
var radTwo = document.getElementById("radTwo");
var radThree = document.getElementById("radThree");
var price;
if (radOne.checked){
price = 15.00;}
else if (radTwo.checked){
price = 20.00;}
else{
price = 25.00;
}
alert("MY PIZZA CAFE \nTotal Price is : "+ price +"");
}
function reset() {
document.getElementById("frm1").reset();
}
</script>

Render Price in external Div

I have found a code to display the final price based on some selections from a form imputs (checkbox) affecting the final price. I want also it to affect an external div with text on it. Is a huge fixed element I've created displaying "Final Cost" and I also want this to render the final price by changing the getElementByID and nothing happened. Could you help me to solve this?
I want also .priceText1 also to be affected:)
Actual code is
HTML
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Candy $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Burger $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Coke $1.99
</label>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
<div class="priceWrapper">
<h3 class="priceText1">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
JS
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
You could simply use innerText with querySelector to add the total price to the element .priceText1 like :
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
Hope this helps.
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Candy $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Burger $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Coke $1.99
</label>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit" />
<input value="Reset" type="reset" />
</form>
<div class="priceWrapper">
<h3 class="priceText1">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>

js radio buttons check

i am trying to add mutliple choice exam questions (like survey) to my site. For that i am using js and jquery. i added feature to make sure all group buttons have been checked. But the error is that I cannot resolve properly checking of selected ones. Js check only first if and if it is true then all questions have been answered true, if not then all answers are wrong.
here is my js code:
function doAjaxPost() {
var result = 4;
var rightAnswers = 0;
var allmarked = 0;
var response = "";
$('.answers').each(function() {
if ($(this).find('input[type="radio"]:checked').length > 0) {
allmarked = allmarked + 1;
} else {
alert("not all checked");
}
});
if (allmarked == result) {
allmarked = 0;
if ($("input[#name=7]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
if ($("input[#name=8]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
if ($("input[#name=9]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
if ($("input[#name=10]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
$('#info').html(rightAnswers + " / " + result);
}
}
here is my html:
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.4</h4>
<br />
<ul class="answers">
<input type="radio" name="9" value="1" id="9a" />
<label for="9a">1</label>
<br/>
<input type="radio" name="9" value="2" id="9b" />
<label for="9b">2</label>
<br/>
<input type="radio" name="9" value="3" id="9c" />
<label for="9c">3</label>
<br/>
<input type="radio" name="9" value="right" id="9d" />
<label for="9d">right</label>
<br/>
</ul>
</div>
</div>
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.5</h4>
<br />
<ul class="answers">
<input type="radio" name="10" value="1" id="10a" />
<label for="10a">1</label>
<br/>
<input type="radio" name="10" value="2" id="10b" />
<label for="10b">2</label>
<br/>
<input type="radio" name="10" value="3" id="10c" />
<label for="10c">3</label>
<br/>
<input type="radio" name="10" value="right" id="10d" />
<label for="10d">right</label>
<br/>
</ul>
</div>
</div>
i am stack to this point. it frankly seems stupid question but i am not spesialized in js. Thus, any assist would be appreciated
Because of this radio group selection, so you can only choose one; if you want to achieve that situation, you need to use checkbox to achieve;and the way to resolve ploblem is every options bind clickevent when clicking one of checkboxes,then the click func can achieve every option choosed
you can try this:
you can create an object with questions and related correct answers:
function doAjaxPost() {
var result = $('.answers').length;
var rightAnswers =0 ;
var response= "" ;
var error=false;
var correct_answers = [{question_number:1,answers_number:5},
{question_number:10,answers_number:2},
{question_number:9,answers_number:3}];
$('.answers').each(function(){
if($(this).find('input[type="radio"]:checked').length > 0){
var question_number=$(this).find('input[type="radio"]:checked').attr("name");
var answer_number =$(this).find('input[type="radio"]:checked').val();
$.each(correct_answers, function( index, value ) {
if(question_number==value.question_number && answer_number==value.answers_number)rightAnswers++;
});
}
else error=true;
});
if(error) alert("not all checked"); //display the error once
else $('#info').html(rightAnswers + " / " + result);
}
$('#check_values').click(function(){
doAjaxPost();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.4</h4> <br />
<ul class="answers">
<input type="radio" name="9" value="1" id="9a" />
<label for="9a">1</label><br/>
<input type="radio" name="9" value="2" id="9b" />
<label for="9b">2</label><br/>
<input type="radio" name="9" value="3" id="9c" />
<label for="9c">3</label><br/>
<input type="radio" name="9" value="4" id="9d" />
<label for="9d">4</label><br/>
</ul>
</div>
</div>
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.5</h4> <br />
<ul class="answers">
<input type="radio" name="10" value="1" id="10a" />
<label for="10a">1</label><br/>
<input type="radio" name="10" value="2" id="10b" />
<label for="10b">2</label><br/>
<input type="radio" name="10" value="3" id="10c" />
<label for="10c">3</label><br/>
<input type="radio" name="10" value="4" id="10d" />
<label for="10d">4</label><br/>
</ul>
</div>
</div>
<input type="button" id="check_values" value="Check"/>
<p id="info"></p>

Categories

Resources