I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.
This new text box should get numbers from the User and add new text fields under the Element for options.
For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:
Option 1 _____________
Option 2 _____________
Option 3 _____________
// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
var type1 = document.getElementById('type1').value;
var type2 = document.getElementById('type2').value;
var question = document.getElementById('question').value;
var counter = 'Element';
counter+= a;
var prviElement=document.createElement('span');
prviElement.textContent= counter + ':' +' ';
document.body.appendChild(prviElement);
var pitanje= document.createElement('span');
var unos='unos';
unos += i;
pitanje.id=unos;
pitanje.textContent=question + ' ';
document.body.appendChild(pitanje);
var tip1 = document.createElement("input");
var element='element';
element += i;
tip1.id=element;
if (type1=='textbox') {
tip1.type=type2
} else {
tip1.type=type1
}
document.body.appendChild(tip1);
var linija1= document.createElement("br");
document.body.appendChild(linija1);
var linija2= document.createElement("br");
document.body.appendChild(linija2);
i++;
a++;
}
function AddTextBox(elm) {
var v = elm.value;
var iCounter = elm.id.replace('type1', '');
if (v == 'radio') {
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.id = 'txtSecond' + iCounter;
elm.parentNode.insertBefore(textbox, elm.nextSibling);
} else {
//Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
var rmv = document.getElementById('txtSecond' + iCounter);
if (rmv != undefined) {
rmv.remove();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="pepo.css">
<meta charset="UTF-8">
<script src="basa.js"></script>
<title>OnlineForms</title>
</head>
<body>
<!--Ovaj kod je za Main Page-->
<Main class="kocka">
<div align="left">
<input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
<button class="dropbtn" id="getAllButton">Forms</button>
</div>
<br>
<div align="left">
<input type="number" id="key" class="dropbtn" Placeholder="Type the key value"/>
<button class="dropbtn" id="getButton"> Search </button>
<br>
<br>
</div>
</Main>
<!--Ovaj kod je za Elemente-->
<div id="element" class="hide">
<h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
<select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
<option selected disabled hidden value="Please select">Please select</option>
<option value="textbox">textbox</option>
<option value="checkbox">checkbox</option>
<option value="radio">radio button</option>
</select>
<select title="ddmenu" class="dropbtn" id="type2">
<option selected disabled hidden value="Please select">Please select</option>
<option value="none">none</option>
<option value="mandatory">mandatory</option>
<option value="number">numeric</option>
</select>
</h1>
<input type="button" id="adddugme" class="dropbtn2" value="Add" onclick="mojaFunkcija()"/>
<br>
<br>
<button id="addButton" class='dropbtn'>Save</button>
</div>
<br>
<br>
<div id="status"></div>
<br>
<div id="status2"></div>
</body>
</html>
The issue is that you are executing the code only one time.
Put it inside a loop.
Here, I made a loop to execute the same code x times where x is the number user entered in the form
Check the snippet
var i = 0;
var a = 1;
function mojaFunkcija() {
var type1 = document.getElementById('type1').value;
var type2 = document.getElementById('type2').value;
var question = document.getElementById('question').value;
var i=0;
while(i<question){
var counter = 'Element';
counter+= a;
var prviElement=document.createElement('span');
prviElement.textContent= counter + ':' +' ';
document.body.appendChild(prviElement);
var pitanje= document.createElement('span');
var unos='unos';
unos += i;
pitanje.id=unos;
pitanje.textContent=(i+1) + ' ';
document.body.appendChild(pitanje);
var tip1 = document.createElement("input");
var element='element';
element += i;
tip1.id=element;
if (type1=='textbox') {
tip1.type=type2
} else {
tip1.type=type1
}
document.body.appendChild(tip1);
var linija1= document.createElement("br");
document.body.appendChild(linija1);
var linija2= document.createElement("br");
document.body.appendChild(linija2);
i++;
a++;
}
}
function AddTextBox(elm) {
var v = elm.value;
var iCounter = elm.id.replace('type1', '');
if (v == 'radio') {
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.id = 'txtSecond' + iCounter;
elm.parentNode.insertBefore(textbox, elm.nextSibling);
} else {
//Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
var rmv = document.getElementById('txtSecond' + iCounter);
if (rmv != undefined) {
rmv.remove();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="pepo.css">
<meta charset="UTF-8">
<script src="basa.js"></script>
<title>OnlineForms</title>
</head>
<body>
<!--Ovaj kod je za Main Page-->
<Main class="kocka">
<div align="left">
<input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
<button class="dropbtn" id="getAllButton">Forms</button>
</div>
<br>
<div align="left">
<input type="number" id="key" class="dropbtn" Placeholder="Type the key value"/>
<button class="dropbtn" id="getButton"> Search </button>
<br>
<br>
</div>
</Main>
<!--Ovaj kod je za Elemente-->
<div id="element" class="hide">
<h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
<select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
<option selected disabled hidden value="Please select">Please select</option>
<option value="textbox">textbox</option>
<option value="checkbox">checkbox</option>
<option value="radio">radio button</option>
</select>
<select title="ddmenu" class="dropbtn" id="type2">
<option selected disabled hidden value="Please select">Please select</option>
<option value="none">none</option>
<option value="mandatory">mandatory</option>
<option value="number">numeric</option>
</select>
</h1>
<input type="button" id="adddugme" class="dropbtn2" value="Add" onclick="mojaFunkcija()"/>
<br>
<br>
<button id="addButton" class='dropbtn'>Save</button>
</div>
<br>
<br>
<div id="status"></div>
<br>
<div id="status2"></div>
</body>
</html>
I think I understand what you're trying to achieve. It seems you're already able to reference the inputbox you want the value from because you're removing it in your AddTextBox function. In which case you can use similar code to loop depending on that value. Something like this:
var cnt = document.getElementById('txtSecond' + iCounter);
if (cnt != undefined && Number.isInteger(parseInt(cnt.value))) {
// loop to create options
}
Read about the Conditional (Ternary) Operator
then simplify your js:
option ? option1 : option2
as for the display, I would use:
if (option === 'option1'){
$('option2).hide() // or show
}
a little jquery in there, and so forth.
Related
These are two html page for a laundry website, one is called the booking page where clients can click to book the number of clothes to be washed and have the total amount to pay, another page called the summary which is suppose to receive data from booking page (no server side language is used, just local storage in JavaScript), but I have not been able to figure it out at all.
I tried using local storage but could not figure it out.
<div class="summaryContainer">
<div class="summaryNavBar"><p className="summaryTitle">Summary</p>
</div>
<div class="summaryContent">
<p class="total" id="total">Total:</p>
<p class="sum">₦0.00</p>
</div>
<div class="summaryCard">
<div class="summary-card-title">
<div>Item</div>
<div>Quantity</div>
</div>
<div class="summary-card-content">
<div >Shirt(s)</div><div id="
first" class="summary-quantity"><button type="button" id="sub"
class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button> </div>
</div>
<div class="summary-card-content">
<div>Trouser(s)</div>
<div class="summary-quantity" id="second">
<button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content" id="third">
<div>Suit(s)</div><div class="summary-quantity"><button
type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button> </div>
</div>
<p class=" more">..more</p>
</div>
<div class="summaryButton">
<button class="button-left"><span><FontAwesomeIcon
class="buttonLeft" icon="angle-left"/></span>Back</button>
<button class="button-right">Proceed to payment<FontAwesomeIcon
class="buttonRight" icon="angle-right"/></button>
</div>
</div>
</body>
</html>
This is the Booking page file
<div class="bookingContainer">
<div>
<div class="booking-container-title">
<p>Book a laundry service</p>
</div>
</div>
<div class="first-booking-container">
<p>What would you like to do ?</p>
<select>
<option class="middle">Dry Clean</option>
<option class="middle">Wash</option>
<option class="middle">Iron</option>
</select>
<FontAwesomeIcon class="select-icon" icon="chevron-down" />
</div>
<!-- First Value -->
<div class="second-booking-container">
<div>
<div class="second-booking-container-image"><img
src="./img/shirt.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_1">
Shirt(s)</p>
<select onchange='totalItem()' class="center" id="first">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id='firstVal'
name="price" max="3" min="1">₦100</p>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/trouser.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_2">
Trouser(s)</p>
<select onchange='totalItem()' class="center" id="second">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="secondVal"
name="price" max="3" min="1">₦100</p>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/skirt.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_3">
Skirt(s)</p>
<select onchange='totalItem()' class="center" id="third">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="thirdVal"
name="price" max="3" min="1">₦100</p>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/blouse.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_4">
Blouse(s)</p>
<select onchange='totalItem()' class="center" id="fourth">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="fourthVal"
name="price" max="3" min="1">₦100</p>
</div>
<div>
src="./img/jacket.png" /></div>
<p class="second-booking-container-icon-long" name="product"
value="100" id="qnty_5">Suit/Jacket(s)
</p>
<select onchange='totalItem()' class="center" id="fifth">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="fifthVal"
name="price" max="3" min="1">₦100</p>
</div>
</div>
<div class="third-booking-container">
<p id="total">Total: <span>₦0.00</span></p>
<button>Set pick up date
<FontAwesomeIcon class="second-container-button-right"
icon="angle-right" /></button>
</div>
</div>
<script src="main.js"></script>
Here is the javascript file
let first = document.querySelector('#first');
let second = document.querySelector('#second');
let third = document.querySelector('#third');
let fourth = document.querySelector('#fourth');
let fifth = document.querySelector('#fifth');
//invoke this function when the input changes on individual
selected elements
const totalItem = () => {
let firstValue = `${first.options[first.selectedIndex].value}`
let secondValue = `${second.options[second.selectedIndex].value}`
let thirdValue =
`${third.options[third.selectedIndex].value}`
let fourthValue = `${fourth.options[fourth.selectedIndex].value}`
let fifthValue = `${fifth.options[fifth.selectedIndex].value}`
console.table(firstValue, secondValue, thirdValue, fourthValue,
fifthValue)
//call function for each cloths and pass 3 values(the selected
number, the constant(₦100) and where to update)
multiplySelectedwithConstVal(firstValue, firstValNo, firstVal);
multiplySelectedwithConstVal(secondValue, secondValNo,
secondVal);
multiplySelectedwithConstVal(thirdValue, thirdValNo, thirdVal);
multiplySelectedwithConstVal(fourthValue, fourthValNo,
fourthVal);
multiplySelectedwithConstVal(fifthValue, fifthValNo, fifthVal);
//total addition of all values
let selectedValArray = [];
const total = () => {
selectedValArray.push(
parseInt(firstVal.innerHTML.replace("₦", "")),
parseInt(secondVal.innerHTML.replace("₦", "")),
parseInt(thirdVal.innerHTML.replace("₦", "")),
parseInt(fourthVal.innerHTML.replace("₦", "")),
parseInt(fifthVal.innerHTML.replace("₦", ""))
);
return selectedValArray.reduce((accu, currentVal) => accu +
currentVal, 0);
}
finalVal.innerHTML = `Total: <span>₦${total()}</span>`
// console.log(total());
}
//target elements that will be updated and
let firstVal = document.querySelector('#firstVal');
let secondVal = document.querySelector('#secondVal');
let thirdVal = document.querySelector('#thirdVal');
let fourthVal = document.querySelector('#fourthVal');
let fifthVal = document.querySelector('#fifthVal');
let finalVal = document.querySelector('#total');
//convert ₦100 to number for multiplication
//converted the innerhtml to number
let firstValNo = parseInt(firstVal.innerHTML.replace("₦", ""));
let secondValNo = parseInt(secondVal.innerHTML.replace("₦", ""));
let thirdValNo = parseInt(thirdVal.innerHTML.replace("₦", ""));
let fourthValNo = parseInt(fourthVal.innerHTML.replace("₦", ""));
let fifthValNo = parseInt(fifthVal.innerHTML.replace("₦", ""));
//multiply selected value with constant and update
const multiplySelectedwithConstVal = (i, k, update) => {
let result = parseInt(i) * k
return update.innerHTML = `₦${result}`
}
I want the value gotten from booking page be effected directly into the summary, the plus and minus button should also be able to add or remove the number of clothes and also change the total amount to be paid.
Add This code in your Initial Page i.e Page 1
let firstVal = document.querySelector('#firstVal');
let secondVal = document.querySelector('#secondVal');
let thirdVal = document.querySelector('#thirdVal');
let fourthVal = document.querySelector('#fourthVal');
let fifthVal = document.querySelector('#fifthVal');
let finalVal = document.querySelector('#total');
localStorage.setItem("firstVal", firstVal);
localStorage.setItem("secondVal", secondVal);
localStorage.setItem("thirdVal", thirdVal);
localStorage.setItem("fourthVal", fourthVal);
localStorage.setItem("fifthVal", fifthVal);
localStorage.setItem("finalVal", finalVal);
Add This code in your Second Page where you want to fetch value i.e Page 2
let firstVal = localStorage.getItem(('firstVal');
let secondVal = localStorage.getItem(('secondVal');
let thirdVal = localStorage.getItem(('thirdVal');
let fourthVal = localStorage.getItem(('fourthVal');
let fifthVal = localStorage.getItem(('fifthVal');
let finalVal = localStorage.getItem(('finalVal');
console.log(firstVal);
console.log(secondVal);
console.log(thirdVal);
console.log(fourthVal);
console.log(fifthVal);
console.log(finalVal);
you can also learn some basic related to local storage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Here is code for Booking Page where localstorage is used to store the count and item value:
<div class="bookingContainer">
<div>
<div class="booking-container-title">
<p>Book a laundry service</p>
</div>
</div>
<div class="first-booking-container">
<p>What would you like to do ?</p>
<select>
<option class="middle">Dry Clean</option>
<option class="middle">Wash</option>
<option class="middle">Iron</option>
</select>
<FontAwesomeIcon class="select-icon" icon="chevron-down" />
</div>
<!-- First Value -->
<div class="second-booking-container">
<div>
<div class="second-booking-container-image"><img
src="./img/shirt.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_1">
Shirt(s)
</p>
<select onchange='totalItem()' class="center" id="first">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id='firstVal'
name="price" max="3" min="1">₦100</p>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/trouser.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_2">
Trouser(s)
</p>
<select onchange='totalItem()' class="center" id="second">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="secondVal"
name="price" max="3" min="1">₦100</p>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/skirt.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_3">
Skirt(s)
</p>
<select onchange='totalItem()' class="center" id="third">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="thirdVal"
name="price" max="3" min="1">₦100</p>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/blouse.png" /></div>
<p class="second-booking-container-icon" name="product"
value="100" id="qnty_4">
Blouse(s)
</p>
<select onchange='totalItem()' class="center" id="fourth">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="fourthVal"
name="price" max="3" min="1">₦100</p>
</div>
<div>
src="./img/jacket.png" />
</div>
<p class="second-booking-container-icon-long" name="product"
value="100" id="qnty_5">Suit/Jacket(s)
</p>
<select onchange='totalItem()' class="center" id="fifth">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<FontAwesomeIcon class="select-long-icon" icon="chevron-
down" />
<p class="second-booking-container-text" id="fifthVal"
name="price" max="3" min="1">₦100</p>
</div>
</div>
<div class="third-booking-container">
<p id="total">Total: <span>₦0.00</span></p>
<button>
Set pick up date
<FontAwesomeIcon class="second-container-button-right"
icon="angle-right" />
</button>
</div>
</div>
<script>
let first = document.querySelector('#first');
let second = document.querySelector('#second');
let third = document.querySelector('#third');
let fourth = document.querySelector('#fourth');
let fifth = document.querySelector('#fifth');
//invoke this function when the input changes on individual
// selected elements
const totalItem = () => {
let firstValue = `${first.options[first.selectedIndex].value}`
let secondValue = `${second.options[second.selectedIndex].value}`
let thirdValue =
`${third.options[third.selectedIndex].value}`
let fourthValue = `${fourth.options[fourth.selectedIndex].value}`
let fifthValue = `${fifth.options[fifth.selectedIndex].value}`
console.table(firstValue, secondValue, thirdValue, fourthValue,
fifthValue)
//call function for each cloths and pass 3 values(the selected
// number, the constant(₦100) and where to update)
multiplySelectedwithConstVal(firstValue, firstValNo, firstVal);
multiplySelectedwithConstVal(secondValue, secondValNo,
secondVal);
multiplySelectedwithConstVal(thirdValue, thirdValNo, thirdVal);
multiplySelectedwithConstVal(fourthValue, fourthValNo,
fourthVal);
multiplySelectedwithConstVal(fifthValue, fifthValNo, fifthVal);
//total addition of all values
let selectedValArray = [];
const total = () => {
selectedValArray.push(
parseInt(firstVal.innerHTML.replace("₦", "")),
parseInt(secondVal.innerHTML.replace("₦", "")),
parseInt(thirdVal.innerHTML.replace("₦", "")),
parseInt(fourthVal.innerHTML.replace("₦", "")),
parseInt(fifthVal.innerHTML.replace("₦", ""))
);
return selectedValArray.reduce((accu, currentVal) => accu +
currentVal, 0);
}
var totalval = total();
finalVal.innerHTML = `Total: <span>₦${totalval}</span>`;
localStorage.clear();
localStorage.setItem("firstVal",firstValNo);
localStorage.setItem("secondVal", secondValNo);
localStorage.setItem("thirdVal", thirdValNo);
localStorage.setItem("fourthVal", fourthValNo);
localStorage.setItem("fifthVal", fifthValNo);
localStorage.setItem("firstValCount", firstValue);
localStorage.setItem("secondValCount", secondValue);
localStorage.setItem("thirdValCount", thirdValue);
localStorage.setItem("fourthValCount", fourthValue);
localStorage.setItem("fifthValCount", fifthValue);
localStorage.setItem("finalVal", totalval);
}
//target elements that will be updated and
let firstVal = document.querySelector('#firstVal');
let secondVal = document.querySelector('#secondVal');
let thirdVal = document.querySelector('#thirdVal');
let fourthVal = document.querySelector('#fourthVal');
let fifthVal = document.querySelector('#fifthVal');
let finalVal = document.querySelector('#total');
//convert ₦100 to number for multiplication
//converted the innerhtml to number
let firstValNo = parseInt(firstVal.innerHTML.replace("₦", ""));
let secondValNo = parseInt(secondVal.innerHTML.replace("₦", ""));
let thirdValNo = parseInt(thirdVal.innerHTML.replace("₦", ""));
let fourthValNo = parseInt(fourthVal.innerHTML.replace("₦", ""));
let fifthValNo = parseInt(fifthVal.innerHTML.replace("₦", ""));
//multiply selected value with constant and update
const multiplySelectedwithConstVal = (i, k, update) => {
let result = parseInt(i) * k
return update.innerHTML = `₦${result}`
}
</script>
Here is code for Summary page with add/ substract logic
<div class="summaryContainer">
<div class="summaryNavBar"><p className="summaryTitle">Summary</p>
</div>
<div class="summaryContent">
<p class="total" id="total">Total:</p>
</div>
<div class="summaryCard">
<div class="summary-card-title">
<div>Item</div>
<div>Quantity</div>
</div>
<div class="summary-card-content">
<div >Shirt(s)</div><div id="
first" class="summary-quantity"><button type="button" id="sub"
class="sub">−</button>
<input type="text" id="firstVal" value="0" class="field" />
<button type="button" id="add" class="add">+</button> </div>
</div>
<div class="summary-card-content">
<div>Trouser(s)</div>
<div class="summary-quantity" id="second">
<button type="button" id="sub" class="sub">−</button>
<input type="text" id="secondVal" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content" id="third">
<div>Suit(s)</div><div class="summary-quantity"><button
type="button" id="sub" class="sub">−</button>
<input type="text" id="thirdVal" value="0" class="field" />
<button type="button" id="add" class="add">+</button> </div>
</div>
<p class=" more">..more</p>
</div>
<div class="summaryButton">
<button class="button-left"><span><FontAwesomeIcon
class="buttonLeft" icon="angle-left"/></span>Back</button>
<button class="button-right">Proceed to payment<FontAwesomeIcon
class="buttonRight" icon="angle-right"/></button>
</div>
</div>
</body>
</html>
<script>
var firstValue = localStorage.getItem('firstVal');
var secondValue = localStorage.getItem('secondVal');
var thirdValue = localStorage.getItem('thirdVal');
var finalValue = localStorage.getItem('finalVal');
var firstValueCount = localStorage.getItem('firstValCount');
var secondValueCount = localStorage.getItem('secondValCount');
var thirdValueCount = localStorage.getItem('thirdValCount');
var finalVal = document.querySelector('#total');
finalVal.innerHTML = `Total: <span>₦${finalValue}</span>`;
document.getElementById('firstVal').value = firstValueCount ;
document.getElementById('secondVal').value = secondValueCount ;
document.getElementById('thirdVal').value = thirdValueCount ;
var first = document.querySelector('#first');
var second = document.querySelector('#second');
var third = document.querySelector('#third');
var fourth = document.querySelector('#fourth');
var fifth = document.querySelector('#fifth');
//invoke this function when the input changes on individual
// selected elements
function calSum(el ,type){
if(type == "add"){
var id = (el.previousSibling.previousElementSibling.id);
var count = parseInt(el.previousSibling.previousElementSibling.value);
// increment count by one
var final_count = (count + 1);
el.previousSibling.previousElementSibling.value = final_count;
}else{
var id = (el.nextSibling.nextElementSibling.id);
var count = parseInt(el.nextSibling.nextElementSibling.value);
// decrement count by one
var final_count = (count - 1);
el.nextSibling.nextElementSibling.value = final_count;
}
var totalSum = parseInt(localStorage.getItem('finalVal'));
var price = 100;
if(id === 'firstVal'){
totalSum = (totalSum + (price * final_count)) -(count *price) ;
localStorage.setItem("firstValCount", final_count);
}else if(id === 'secondVal'){
totalSum = (totalSum + (price * final_count)) -(count *price);
localStorage.setItem("secondValCount", final_count);
}else if(id === 'thirdVal'){
totalSum = (totalSum + (price * final_count)) -(count *price) ;
localStorage.setItem("thirdValCount", final_count);
}
console.log(totalSum);
localStorage.setItem("finalVal", totalSum);
document.querySelector('#total').innerHTML = `Total: <span>₦${totalSum}</span>`;
}
var classname = document.getElementsByClassName("add");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', function(){
calSum(this,'add');
} , false);
}
var sub = document.getElementsByClassName("sub");
for (var i = 0; i < sub.length; i++) {
sub[i].addEventListener('click', function(){
calSum(this,'sub');
} , false);
}
</script>
I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>
Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.
i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>
Alright, so I am stuck. So the break down of the project is when you enter your age, and select an option from the drop down list when you click add, a list is created and that input is plugged into the list. I have to also show that list somewhere on the page. I hope I explained that correctly.
Anyways, I've been trying everything from trying to create a new div, to creating an unordered list programmatically, and trying to display it within the body under the last div, but my code below doesn't execute when I hit the add button. By the way I CAN NOT edit the HTML in anyway and I CAN NOT use JQuery. I have to use pure Javascript. Any tips or help would be great!
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
var add = document.getElementsByClassName('add');
add.onlick = 'addToList()';
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function addToList() {
var li = document.createElement("li");
//li.setAttribute('id', age.value + dropDown.value);
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<h1>Household List</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
There was some syntactical errors in the code, especially the button click event handler. Here is the correct code.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
var add = document.getElementsByClassName('add');
add[0].onclick = addToList;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function addToList() {
var li = document.createElement("li");
//li.setAttribute('id', age.value + dropDown.value);
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<h1>Household List</h1>
<div class="builder">
<ol class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
There are numerous issues in your code
All the for attributes and input attributes can be defined the html instead of using js
button type default is submit ,so add button type="button" in <button class="add">add</button>
add.onlick = 'addToList()'; is wrong ;the function is not a string , replace it with document.getElementsByClassName('add')[0].onclick = addToList;
var age = document.getElementsByName("age")[0];
var dropDown = document.getElementsByName("rel")[0];
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
document.getElementsByClassName('add')[0].onclick = addToList;
function addToList() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<body>
<h1>Household List</h1>
<div class="builder">
<o class="household"></o>
<form method="POST" action="form-handler">
<div>
<label>Age
<input type="number" name="age" min="0" max="120">
</label>
</div>
<div>
<label>Relationship
<select name="rel" required>
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add" type="button">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
</body>
There is a problem with your HTML you have an o tag instead of an order list tag. This may fix the code. Also when you click on the add button the form is posted so I would remove the post until the end.
presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box','div');">
</div>
</body>
<script>
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
var counter = 1;
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
</script>
<script>
function removeElement(boxDiv, divDiv){
if (divDiv == boxDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(divDiv)) {
var div = document.getElementById(divDiv);
var box = document.getElementById(boxDiv);
box.removeChild(div);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
You are passing the string div to your remove element function which will only remove the first div.
You can find all the children elements and then remove the last child
Building on your previous code, see the snippet below
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
console.log(template);
var counter = 1;
submit1=document.getElementById("submit1");
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
function removeElement(boxDiv){
var box = document.getElementById(boxDiv);
if(box.children){
console.log(box.children);
box.children[box.children.length-1].outerHTML="";
}
}
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box');">
</div>
It might be because js thinks you're only selecting the last one when doing
var div = document.getElementById(divDiv);
Try doing a loop until document.getElementById(divDiv) is undefined
I'm designing a online car shop as part of a small exercise. Everything going smoothly except for the total price. I want the selections to add on to the running total, depending on what radio button and check box I select, rather than each time a selection is made, the value of that selection accumulating on to my total. I hope I made explained that properly, I'd appreciate any help anyone can give!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Configure Your GT Sports Car</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<header>
<h1>Configure your GT Super Sportscar</h1>
</header>
</div></div></div>
<form name="SportsCar" id="SportsCar">
<p>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<h3>Configuration</h3>
<input type="radio" name="format" id = "Manual" value="27790.00">
<label for = "Manual">GT Manual - €27,790.00</label>
<br>
<input type="radio" name="format" id = "Automatic" value="28590.00">
<label for = "Automatic">GT Automatic - €28,590.00</label>
<br>
<input type="radio" name="format" id = "Smanual" value="32455.00">
<label for = "Smanual">GT-S Manual - €32,455.00</label>
<br>
<input type="radio" name="format" id = "Sautomatic" value="33155.00">
<label for = "Sautomatic">GT-S Automatic - €33,155.00</label>
<br>
</div>
<div class="col-md-6">
<h3>Car Colours</h3>
<label for = "colour" >Please select a colour</label>
<select name="colour" id="colour">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="silver">Silver</option>
<option value="white">White</option>
</select>
<img id="carImage" img src="images/black.jpg" alt="target_blank">
</div></div></div></div>
<div class="row">
<div class="col-md-12">
<h3>Factory Options</h3>
<input type="radio" name="fOptions" id="combo1" value="1235.00">
<label for="combo1">Option Combo 1 - €1,235.00</label>
<br>
(Power windows, Doors, Cruise Control)
<br>
<input type="radio" name="fOptions" id="combo2" value="3354.00">
<label for="combo2">Option Combo 2 - €3,354.00</label>
<br>
(Rear spoiler & Fog Lamps, Key-less Entry, Power Tilt & Slide Moonroof, Power windows, Doors, Cruise Control)
<br>
<input type="radio" name="fOptions" id="noExtras" value="0.00">
<label for="noExtras">No Extras - €0</label>
</div></div>
<br>
<div class="row">
<div class="col-md-12">
<h3>Dealer Options</h3>
<input type="checkbox" name="dealer" id="autochanger" value="550.00">
<label for = "auto-changer">CD Auto-Changer - €550.00</label>
<br>
<input type="checkbox" name="dealer" id="security" value="399.00">
<label for = "security">VIP Security System - €399.00</label>
<br>
<input type="checkbox" name="dealer" id="mirror" value="295.00">
<label for = "mirror">Auto Dimming Mirror - €295.00</label>
<br>
</div></div>
<div class="row">
<div class="col-md-12">
<br>
<label for="total" class="control-label col-md-2">Total Cost</label>
<input type="text" name="total" id="total" maxlength="3" readonly>
</div></div>
</p>
</form>
</div>
</body>
<script type="text/javascript">
var source = new Array();
window.addEventListener("load", preLoad, false);
function preLoad(){
source[0]="images/black.jpg";
source[1]="images/blue.jpg";
source[2]="images/red.jpg";
source[3]="images/silver.jpg";
source[4]="images/white.jpg";
}
carColour = document.getElementById("colour");
function handleColour(){
if(carColour.selectedIndex==0)
{
theImage.src=source[0];
}
else if(carColour.selectedIndex==1)
{
theImage.src=source[1];
}
else if(carColour.selectedIndex==2)
{
theImage.src=source[2];
}
else if(carColour.selectedIndex==3)
{
theImage.src=source[3];
}
else if(carColour.selectedIndex==4)
{
theImage.src=source[4];
}
}
theImage=document.getElementById("carImage");
carColour.addEventListener("click", handleColour, false);
</script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/calculate.js"></script>
</html>
Javascript
function formatCurrency(num) {
num = num.toString().replace(/\€|\,/g,'');
if(isNaN(num))
{num = "0";}
sign = (num == (num = Math.abs(num)));
num = num.toFixed(2);
elements= num.split(".");
num = elements[0];
cents = elements[1];
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
{num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*0+3));}
return (((sign)?'':'-') + '€' + num + '.' + cents)
}
window.addEventListener("load", handleLoad, false);
function handleLoad(){
runningTotal=parseInt(document.getElementById("Manual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
cars = document.getElementById("Manual");
cars.addEventListener("click", handleConfig, false);
function handleConfig(){
if(manual.checked){
runningTotal = parseInt(document.getElementById("manual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Automatic");
cars.addEventListener("click", handleConfigOne, false);
function handleConfigOne(){
if(Automatic.checked){
runningTotal = parseInt(document.getElementById("Automatic").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Smanual");
cars.addEventListener("click", handleConfigTwo, false);
function handleConfigTwo(){
if(Smanual.checked){
runningTotal = parseInt(document.getElementById("Smanual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Sautomatic");
cars.addEventListener("click", handleConfigThree, false);
function handleConfigThree(){
if(Sautomatic.checked){
runningTotal = parseInt(document.getElementById("Sautomatic").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var option = document.getElementById("combo1");
option.addEventListener("click", handleClick, false);
function handleClick(){
if(combo1.checked)
{
list=parseInt(document.getElementById("combo1").value);
runningTotal+=list;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var factory = document.getElementById("combo2");
factory.addEventListener("click", handleExtrasTwo, false);
function handleExtrasTwo(){
if(combo2.checked)
{
list=parseInt(document.getElementById("combo2").value);
runningTotal+=list;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var extras = document.getElementById("noExtras");
extras.addEventListener("click", handleNoExtras, false);
function handleNoExtras(){
if(noExtras.checked)
{
var noList=parseInt(document.getElementById("noExtras").value);
runningTotal += noList;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOptions = document.getElementById("autochanger");
dealerOptions.addEventListener("click", handleOptions,false);
function handleOptions(){
if(autochanger.checked)
{
autoChange=parseInt(document.getElementById("autochanger").value);
runningTotal +=autoChange;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOption = document.getElementById("security");
dealerOption.addEventListener("click", handleOptionsTwo,false);
function handleOptionsTwo(){
if(security.checked)
{
secure=parseInt(document.getElementById("security").value);
runningTotal+=secure;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOptionThree = document.getElementById("mirror");
dealerOptionThree.addEventListener("click", handleOptionThree,false);
function handleOptionThree(){
if(mirror.checked)
{
mirror=parseInt(document.getElementById("mirror").value);
runningTotal += mirror;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
As you already have jquery included in your page, you should use it. It makes your life so much simpler. Using your code as a base, I've created a simple method to sum the values of the selected elements (radio or checkbox), and display it on the total textbox.
Then you will not have to put all those click events.
Check it out: (see the running example on this fiddle: http://jsfiddle.net/b3p4r/)
$("input").change(function() {
var total = 0;
$("input").each(function() {
if($(this).is(":checked"))
total += parseFloat($(this).val());
});
$("#total").val(formatCurrency(total));
});