I'm trying to add elements dynamically through javascript but whenever I try opening up the page they appear for a split second then disappear
I take a number of process from the input tag and run a loop to create each element individually
I tried removing everything from the event and only call a function which I placed the code in but didn't work
const numberOfProcesses = document.getElementById("numberOfProcesses").value;
const timeQuantum = document.getElementById("timeQuantum").value;
const start = document.getElementById("start");
const processDiv = document.getElementById("processDiv");
const burstDiv = document.getElementById("burstDiv");
start.addEventListener("click", (event) => {
for (let i = 0; i < numberOfProcesses; i++) {
let pLabel = document.createElement("label");
pLabel.setAttribute("id", `process ${i}`);
pLabel.innerText = `Process ${i}`;
let pInput = document.createElement("input");
pInput.setAttribute("type", "number");
pInput.setAttribute("id", `process ${i}`);
let bLabel = document.createElement("label");
bLabel.setAttribute("id", `burstTime ${i}`);
bLabel.innerText = `Burst Time ${i}`;
let bInput = document.createElement("input");
bInput.setAttribute("type", "number");
bInput.setAttribute("id", `burstTime ${i}`);
processDiv.appendChild(pLabel);
processDiv.appendChild(pInput);
burstDiv.appendChild(bLabel);
burstDiv.appendChild(bInput);
console.log(pLabel, pInput, bLabel, bInput);
}
});
<form action="">
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button id="start">Start</button>
</form>
</section>
<br /><br />
<section>
<form action="">
<div id="processDiv">
<label for="process0">P0</label>
<input type="number" name="process" id="process0" />
</div>
<div id="burstDiv">
<label for="burstTime0">Burst Time</label>
<input type="number" name="burst time" id="burstTime0" />
</div>
<button id="excute">Execute</button>
</form>
Remove action="" and set type attribute to button if nothing is submitted. The behaviour you describe is due to the form being submitted.
Do like this and you can see you console log for other errors:
<form>
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button type="button" id="start">Start</button>
</form>
My code updates the CPC textbox when options are selected, but when an agency discount is selected (i.e. the 10% checkbox), it successfully lowers the CPC textbox value by 10% but does not do the same for the Total Cost textbox.
The Total Cost textbox value should be the (CPC textbox value * number of clicks textbox) * percentdiscount multiplier
Can anyone see where I'm going wrong? I'll be happy to clarify further if I haven't explained this very well!
HTML:
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" onclick="BlacklistFunction()">Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" onclick="calculatetotalcost10()" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" onclick="calculatetier15()" >
15% Discount
</label>
</div>
Javascript:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
//to work out total cost
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
Looks like you are calculatetier function isn't being called during the change of discount.
Working Demo: https://codepen.io/punith/pen/gOpaVxr?editors=1010
HTML code
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" >Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" >
15% Discount
</label>
</div>
JS Code
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
if(myBox6=="0.00"){
myBox6 =1;
}
console.log(myBox6)
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
//to work out total cost
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
calculatetier()
}
});
try to use onchange event instead I guess the event you are binding is not correct
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" onchange="calculatetier()" />
How to add a function inside a For Loop. I'm trying to add a feature to increase the cost with increase in product. But Unable to add this inside a For-loop.
Html
<div class="slider-vertical"></div>
<div id="purhcaseForm">
<form id="purchase">
<br> Please Select Quantity
<input type='button' name='subtract' onclick='Total("qty",-1,"total",250);' value='-'/>
<input type='button' name='add' onclick='Total("qty",1,"total",250);' value='+'/>
<input type='text' name='qty' id='qty' readonly=true value="0"/>
<input type='text' name='total' id='total' value="0" />
</form>
</div>
For-Loop
for ( var i=0; i<Boys.length; i++ ){
Boys_Toys += '<div class="card"> <h2>'+Boys[i].name+'</h2> <img src='+Boys[i].image+' style="width:250px" border="3px"><p class="Cost">$ '+Boys[i].Cost+'</p> <p> <button> Add to cart </button> </p> <div class="slider-vertical"> <div id="purhcaseForm"> <form id="purchase"> <p> Please Select Quantity </p> <input type="button" name="subtract" onclick="Total(\'qty\',-1,\'total\',250);" value="-"/> <input type="button" name="add" onclick="Total(\'qty\',1,\'total\',250);" value="+"/> <input type="text" name="qty" id="qty" readonly=true value="0"/> <input type="text" name="total" id="total" value="0" /> </div></form> </div> </div>';
}
Function
function Total(qty, ud, total, value, cart) {
qty = document.getElementById("qty",);
ud > 0 ? qty.value++ : qty.value--;
qty.value = Math.max(qty.value, 0);
document.getElementById("total",).value = qty.value * value;
}
Expected to increase each product cost with quantity.
<script>
var Boys = [{name:"Rubix cube", Cost:250, image:"Pictures/3x3-Rubix-Cube.jpg"},
{name:"Drone", Cost:5000, image:"Pictures/Rc.Drone.jpg"},
{name:"Aeroplane", Cost:3000, image:"Pictures/Rc.Plane.jpg"},
{name:"Cars", Cost:1500, image:"Pictures/Rc.Car.jpg"},
{name:"Rc.Hellio", Cost:1000, image:"Pictures/Rc.Hellio.jpg"},
{name:"Brown Teddy", Cost:800, image:"Pictures/Teddy.jpg"}];
//var products = [document.getElementById("purhcaseForm","purchase")];
//var Cost = [250, 50000, 3000, 1500, 1000, 800];
var Quantity = [document.getElementById("total","qty")];
var Boys_Toys= " ";
//var images = ["Pictures/3x3-Rubix-Cube.jpg","Pictures/Rc.Drone.jpg","Pictures/Rc.Plane.jpg","Pictures/Rc.Car.jpg","Pictures/Rc.Hellio.jpg" ,"Pictures/Teddy.jpg"];
for ( var i=0; i<Boys.length; i++ ){
Boys_Toys += '<div class="card"> <h2>'+Boys[i].name+'</h2> <img src='+Boys[i].image+' style="width:250px" border="3px"><p class="Cost">$ '+Boys[i].Cost+'</p> <p> <button> Add to cart </button> </p> <div class="slider-vertical"> <div id="purhcaseForm"> <form id="purchase"> <p> Please Select Quantity </p> <input type="button" name="subtract" onclick="Total(\'qty\',-1,\'total\',250);" value="-"/> <input type="button" name="add" onclick="Total(\'qty\',1,\'total\',250);" value="+"/> <input type="text" name="qty" id="qty" readonly=true value="0"/> <input type="text" name="total" id="total" value="0" /> </div></form> </div> </div>';
}
//for ( var i=0; i<Quantity.length;i++){
//Quantity += '<div class="slider-vertical"><h2>'+Quantity[i].name+'</h2></div>';
//}
console.log(Boys_Toys);
document.getElementById("cart").innerHTML= Boys_Toys;
function Total(qty, ud, total, value, cart) {
qty = document.getElementById("qty",);
ud > 0 ? qty.value++ : qty.value--;
qty.value = Math.max(qty.value, 0);
document.getElementById("total",).value = qty.value * value;
}
</script>
<!DOCTYPE html>
<html>
<head>
<style>
.card {
width:300px;
height:500px;
float:left;
}
.product_image {
width: 49px;
height:150px;
border: 5px #000000 solid;
}
</style>
<script type="text/javascript" src=""></script>
<title>Toy-World.</title>
</head>
<body bgcolor="#cbc8c8">
<div class="slider-vertical"></div>
<div id="purhcaseForm">
<form id="purchase">
<br> Please Select Quantity
<input type='button' name='subtract' onclick='Total("qty",-1,"total",250);' value='-'/>
<input type='button' name='add' onclick='Total("qty",1,"total",250);' value='+'/>
<input type='text' name='qty' id='qty' readonly=true value="0"/>
<input type='text' name='total' id='total' value="0" />
</form>
</div>
</body>
<h1 align="Center"> <u>Toy-World</u> </h1>
<div id="cart"></div>
</div>
</body>
</html>
[Each product has a value already given trying to use this feature in a for loop to increase the cost with quantity.
You first have to consider and make sure what you want to accomplish. My guess is that the first line should be total price, and than you want to have price and quantity for each product, then when the users push Add to cart button you want to push the items from that product to the total price.
In order to do that you first have to give different id's to your generated elements. In your code every qty input has id='qty' and every price input has id='price'. You should always avoid having more elements with same id. In order to fix that you can use the same i you use for indexing.
Then, when you call the Total function you don't really need the qty string or total string. You can just use them in the function. But what you need is the index to know witch element was added or substracted. You also don't use the card variable anywhere so if you don't need it, get rid of it.
After you need an addToCart function to actually update the total price. But in order to be able to modify the price you need to keep records for each product. So if the user selects 10 products, add them to cart, then remove (or add another) 4, then if he push the add to cart button again, you know from where, and how much you need to substract.
I did a working example. I hope I didn't misunderstood, but please try to be more clear in the future :)
var Boys = [{name:"Rubix cube", Cost:250, image:"Pictures/3x3-Rubix-Cube.jpg"},
{name:"Drone", Cost:5000, image:"Pictures/Rc.Drone.jpg"},
{name:"Aeroplane", Cost:3000, image:"Pictures/Rc.Plane.jpg"},
{name:"Cars", Cost:1500, image:"Pictures/Rc.Car.jpg"},
{name:"Rc.Hellio", Cost:1000, image:"Pictures/Rc.Hellio.jpg"},
{name:"Brown Teddy", Cost:800, image:"Pictures/Teddy.jpg"}];
//var products = [document.getElementById("purhcaseForm","purchase")];
//var Cost = [250, 50000, 3000, 1500, 1000, 800];
var Quantity = [document.getElementById("total","qty")];
var Boys_Toys= " ";
//var images = ["Pictures/3x3-Rubix-Cube.jpg","Pictures/Rc.Drone.jpg","Pictures/Rc.Plane.jpg","Pictures/Rc.Car.jpg","Pictures/Rc.Hellio.jpg" ,"Pictures/Teddy.jpg"];
for ( let i=0; i<Boys.length; i++ ){
Boys_Toys += '<div class="card"> <h2>'+Boys[i].name+'</h2> <img src='+Boys[i].image+' style="width:250px" border="3px"><p class="Cost">$ '+Boys[i].Cost+'</p> <p> <button onclick="AddToCart('+i+');"> Add to cart </button> </p> <div class="slider-vertical"> <div id="purhcaseForm"> <form id="purchase"> <p> Please Select Quantity </p> <input type="button" name="subtract" onclick="Total(-1,'+Boys[i].Cost+','+i+');" value="-"/> <input type="button" name="add" onclick="Total(1,'+Boys[i].Cost+','+i+');" value="+"/> <input type="text" name="qty" id="qty'+i+'" readonly=true value="0"/> <input type="text" name="total" id="total'+i+'" value="0" /> </div></form> </div> </div>';
}
document.getElementById("cart").innerHTML= Boys_Toys;
let totalValues = [];
function Total(ud, value, index) {
let qty = document.getElementById("qty" + index).value;
ud > 0 ? qty++ : qty--;
qty = Math.max(qty, 0);
console.log(`total${index} && qty=${qty} && value=${value} && ud=${ud}`);
document.getElementById("qty" + index).value = qty;
document.getElementById("total"+index).value = qty * value;
}
function AddToCart(index) {
totalValues[index] = Number(document.getElementById("total"+index).value);
let totalPrice = 0;
for(value of totalValues) {
totalPrice +=value
}
document.getElementById("total-price").value = totalPrice;
}
.card {
width:300px;
height:500px;
float:left;
}
.product_image {
width: 49px;
height:150px;
border: 5px #000000 solid;
}
<div class="slider-vertical"></div>
<div id="purhcaseForm">
<form id="purchase">
<br> Total Price:
<input type='text' readonly=true name='total' id='total-price' value="0" />
</form>
</div>
</body>
<h1 align="Center"> <u>Toy-World</u> </h1>
<div id="cart"></div>
</div>
How do i automatically display every time I input number and calculate it.
Then the pick button will trigger to calculate the price, my base price would be 100. so if its 2 layers it will be 200 ,
<br> Layer <input type="number" min="1" id="cake_layer" name="cake_layer" /> <!-- onchange="updateTotal()" -->
<input type="button" value="Pick" id="choose" />
<br>
Layer inputed <div class="layer_display"> </div>
<br>
Layer Amount <div class="layer_amt"> </div>
I really need help. thank you !!!
Is this what you want to do?
var cakeLayer = document.getElementById("cake_layer"),
price = 100,
layerDisplay = document.getElementsByClassName("layer_display")[0],
layerAmt = document.getElementsByClassName("layer_amt")[0];
cakeLayer.onchange = function(event) {
var amount = this.value || 0,
totalPrice = amount * price;
layerDisplay.innerText = totalPrice;
layerAmt.innerText = amount;
}
<input type="number" min="1" id="cake_layer" name="cake_layer" />
<!-- onchange="updateTotal()" -->
<input type="button" value="Pick" id="choose" />
<br> total price
<div class="layer_display"> </div>
<br> Layer Amount
<div class="layer_amt"> </div>
You can achieve this by using JavaScript or jQuery. That's the only way to manipulate the DOM.
See this working jsfiddle I made:
https://jsfiddle.net/jw6q53fz/1/
HMTL
<div>
<label for="cake_layer">Layer</label>
<input type="number" class="cake_layer" name="cake_layer" id="cake_layer"/>
<button id="choose">Pick</button>
</div>
<div>
<p>Layer inputed: <span class="layer_display"> </span></p>
<p>Layer Amount: <span class="layer_amt"> </span></p>
</div>
jQuery
$('#choose').on('click', function(){
var cakeLayerValue = $('#cake_layer').val();
$('.layer_display').html(cakeLayerValue);
$('.layer_amt').html(cakeLayerValue * 100);
});
I have following code:
<div>
<input data-maxsale="9" data-maxsaleid="27595" name="cart[3839][qty]" value="1" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27595">
<p>
placeholder
</p>
</div>
</div>
<div>
<input data-maxsale="3" data-maxsaleid="27757" name="cart[3841][qty]" value="1" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27757">
<p>
placeholder
</p>
</div>
</div>
var maxSalInput = $('input[data-maxsaleid]');
$('.maxsalenotifcation').hide();
maxSaleInputs.each(function() {
var maxSaleID = $(this).attr('data-maxsaleid');
var maxSaleValue = $(this).val();
var maxSaleQuantity = $(this).attr('data-maxsale');
if (maxSaleValue > maxSaleQuantity) {
$('.maxsalenotifcation .maxsaleid-' + maxSaleID).show();
}
});
http://jsfiddle.net/bmpqo69g/
I want to display the placeholder separately for each maxsaleid when the input value is bigger than the maxSaleValue.
I can modify the html markup if needed.
How can i do this?
This maxSaleInputsvariable has not been defined.
You should define multiple classes like this $('.maxsalenotifcation.maxsaleid-' + maxSaleID) (without space in between classes)
Code Snippets:
$(function() {
var maxSalInput = $('input[data-maxsaleid]');
$('.maxsalenotifcation').hide();
maxSalInput.each(function() {
var maxSaleID = $(this).attr('data-maxsaleid');
var maxSaleValue = parseInt($(this).val());
var maxSaleQuantity = parseInt($(this).attr('data-maxsale'));
if (maxSaleValue > maxSaleQuantity) {
$('.maxsalenotifcation.maxsaleid-' + maxSaleID).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input data-maxsale="9" data-maxsaleid="27595" name="cart[3839][qty]" value="10" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27595">
<p>
placeholder
</p>
</div>
</div>
<div>
<input data-maxsale="3" data-maxsaleid="27757" name="cart[3841][qty]" value="4" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27757">
<p>
placeholder
</p>
</div>
</div>