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>
Related
I'm trying to change the value of my input box by changing two different select options.
The first select box is product_type with two different data attributes on the options: data-price and data-price_c.
The second Select box pay_type is to selecting between data-price or data-price_c, to update the value of lprice.
This is what I've tried:
var sp = document.getElementById('select_product');
var lp = document.getElementById('lprice');
var count = document.getElementById('count');
var fp = document.getElementById('price');
var pt = document.getElementById('paytype');
var selected_type = pt.options[pt.selectedIndex];
sp.onchange = function(){
var selected = sp.options[sp.selectedIndex];
if (selected_type === 1){
lp.value = selected.getAttribute('data-price');
} else {
lp.value = selected.getAttribute('data-price_c');
}
fp.value = "";
};
sp.onchange();
count.onchange = function(){
fp.value = lp.value * count.value;
}
<div>
<label for="select_product">Select Product</label>
<select name="product_id" id="select_product" onchange="update();">
<option value="1" data-price="10000" data-price_c="11000">Product 1</option>
<option value="2" data-price="20000" data-price_c="21000">Product 2</option>
<option value="3" data-price="30000" data-price_c="31000">Product 3</option>
</select>
</div>
<div>
<label for="paytype">Pay type:</label>
<select name="paytype" id="paytype">
<option value="1">Cash</option>
<option value="2">Dept</option>
</select>
</div>
<div>
<label for="lprice">Single Price:</label>
<input type="text" name="lprice" id="lprice" class="form-control" tabindex="1" readonly/>
</div>
<div>
<label for="count">Count:</label>
<input type="number" name="count" id="count" class="form-control" tabindex="1" />
</div>
<div>
<label for="price">Full Price:</label>
<input type="text" name="price" id="price" class="form-control" tabindex="1" readonly/>
</div>
I hope I understated you correctly what needs to be done from code and explanation:
Your first problem was that you had your selected_type outside of you onchange function so it wasn't getting the changed options onchange.
Second is that you where trying to compare values 1 & 2 with element without actually extracting those values from element (missing .value on selected_type)
I assumed you will need to update the values on your Pay type change too as well as Select Product, so there is nit trick to wrap both HTML selects into one div in this case div id="wrapper" and that will listen on both selects and call function if any of them are changed. So now you call it on wrapper.onchange.
I would also advise to put your calculation fp.value = lp.value * count.value; inside this function to update total price on change of any of those elements so I wrapped your Count: into wrapper div.
Hope this helps.
var sp = document.getElementById('select_product');
var lp = document.getElementById('lprice');
var count = document.getElementById('count');
var fp = document.getElementById('price');
var pt = document.getElementById('paytype');
var wrapper=document.getElementById('wrapper');
wrapper.onchange = function(){
var selected = sp.options[sp.selectedIndex];
var selected_type = pt.options[pt.selectedIndex].value;
if (selected_type === "1"){
lp.value = selected.getAttribute('data-price');
}
if (selected_type === "2"){
lp.value = selected.getAttribute('data-price_c');
}
fp.value = "";
fp.value = lp.value * count.value;
};
wrapper.onchange();
<div id="wrapper">
<div>
<label for="select_product">Select Product</label>
<select name="product_id" id="select_product" >
<option value="1" data-price="10000" data-price_c="11000">Product 1</option>
<option value="2" data-price="20000" data-price_c="21000">Product 2</option>
<option value="3" data-price="30000" data-price_c="31000">Product 3</option>
</select>
</div>
<div>
<label for="paytype">Pay type:</label>
<select name="paytype" id="paytype">
<option value="1">Cash</option>
<option value="2">Dept</option>
</select>
</div>
<div>
<label for="lprice">Single Price:</label>
<input type="text" name="lprice" id="lprice" class="form-control" tabindex="1" readonly/>
</div>
<div>
<label for="count">Count:</label>
<input type="number" name="count" id="count" class="form-control" tabindex="1" />
</div>
</div>
<div>
<label for="price">Full Price:</label>
<input type="text" name="price" id="price" class="form-control" tabindex="1" readonly/>
</div>
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.
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.
I am still attempting to create blank fields that users can add on the fly. I am attempting to clone the following hidden template but I can't get it to add.
My HTML
<div class="_100">
<fieldset id="FieldBlank">
<div id="readroot" class="hidden">
<div class="_100">
<div class="_50"> QA Sample ID:<input type="text" id="QASampleID" name="QASampleID"></div>
<div class="_50" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label>Collection Method</label><br />
<input type="radio" id="radGrab1" value="Grab" name="Collection1" />
<label for="radGrab1">Grab</label>
<input type="radio" id="radEWI1" value="EWI" name="Collection1" />
<label for="radEWI1">EWI</label></div>
</div>
<div class="_100">
<div class="_40">
<label class="analysis-label" for="analysis">Analyte:</label>
<select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "TN">TN</option>
<option value = "TP,NO2+3">TP,NO2+3</option>
</select></div>
<div class="_30">
<label class="preserve-label" for="preserve">Preserved</label>
<select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "HNO3">HNO₃</option>
<option value = "H2SO4">H₂SO₄</option>
</select></div>
<div class="_30">
<label class="cool-label" for="cool">Cooled</label>
<select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "Ice">Ice</option>
<option value = "Frozen">Frozen</option>
<option value = "None">None</option>
</select></div>
</div>
</div>
</fieldset>
</div>
<button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
<hr /><div id="writeroot"> </div>
My javascript
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
I just cannot get it to work! Is it because this script is not jquery? It doesn't seem to be because it is hidden because when I unhide it the button still doesn't work to add the clones? I am so pulling my hair out right now. I need you help!
Have you tried something like:
$("#readroot input").clone().appendTo("body"); // Or wherever you want to append them to
And, yeah, don't hide stuff manually. Use jQuery's toggle function instead:
$("#readroot").toggle(); // Or hide()
Even if i have selected an options it still alert a message "Please choose something."
I got this working with only one dropdown list, but i have problems when there are two or more.
(In working example variable sport is document.getElementById("sports") and only one dropdown list)
What's the issue?
<script type="text/javascript">
function check() {
sport = document.getElementsByClassName("sports");
sport_selected = sport.selectedIndex;
weight = document.getElementById("weight").value;
time = document.getElementById("time").value;
if (sport_selected > 0) {
if (isNaN(weight, time)) {
alert("Error. This is not a number.");
}
else {
met = sport.options[sport_selected].value;
calculations = (time * ((met * 3.5 * weight)/200));
result = Math.round(calculations);
document.lastform.output.value = result + " kcal";
}
}
else {
alert("Please choose something.")
}
});
</script>
<div id="tabs">
<ul>
<li>Running</li>
<li>Walking</li>
</ul>
<div id="tabs-1">
<form name="form1">
<select class="sports">
<option value="">-Choose-</option>
<option value="6">Jog/walk combination</option>
<option value="7">Jogging, general</option>
<option value="8">Running, 5 mph (12 min/miile)</option>
<option value="9">Running, 5.2 mph (11.5 min/mile)</option>
<option value="10">Running, 6 mph (10 min/mile)</option>
</select>
</form>
</div>
<div id="tabs-2">
<form name="form2">
<select class="sports">
<option value="">-Choose-</option>
<option value="2">Walking, general</option>
<option value="2">Walking, 1 mph</option>
</select>
</form>
</div>
</div>
<form name="lastform">
<label for="weight">Weight [kg]:</label><br />
<input type="text" size="3" id="weight"><br />
<label for="time">Duration [min]:</label><br />
<input type="text" size="3" id="time">
<input type="button" value="Calc" onClick="check()"><br /><br />
<label for="kcal">You have burned:</label><br />
<input type="text" id="output">
</form>
getElementsByClassName is returning a collection but not just one item, you need to write code to iterate the collection if you have more controls. please check: https://developer.mozilla.org/en/DOM/document.getElementsByClassName
What about using jQuery, since you've used the TAG ?
HTML
<div id="tabs">
<ul>
<li>Running</li>
<li>Walking</li>
</ul>
<div id="tabs-1">
<form name="form1">
<select class="sports">
<option value="">-Choose-</option>
<option value="6">Jog/walk combination</option>
<option value="7">Jogging, general</option>
<option value="8">Running, 5 mph (12 min/miile)</option>
<option value="9">Running, 5.2 mph (11.5 min/mile)</option>
<option value="10">Running, 6 mph (10 min/mile)</option>
</select>
</form>
</div>
<div id="tabs-2">
<form name="form2">
<select class="sports">
<option value="">-Choose-</option>
<option value="2">Walking, general</option>
<option value="2">Walking, 1 mph</option>
</select>
</form>
</div>
</div>
<form name="lastform">
<label for="weight">Weight [kg]:</label><br />
<input type="text" size="3" id="weight"><br />
<label for="time">Duration [min]:</label><br />
<input type="text" size="3" id="time">
<input type="button" value="Calc" id="check"><br /><br />
<label for="kcal">You have burned:</label><br />
<input id="result" type="text" id="output">
</form>
javascript
$("#check").click(function() {
var sport_selected = $(".sports option:selected").val();
var weight = $("#weight").val();
time = $("#time").val();
if (parseInt(sport_selected) > 0) {
if (isNaN(weight, time)) {
alert("Error. This is not a number.");
}
else {
var met = sport_selected
calculations = (time * ((met * 3.5 * weight) / 200));
result = Math.round(calculations);
$("#result").val(result + " kcal");
}
}
else {
alert("Please choose something.")
}
});
and this is the fiddle.