how to count sum price from an appended object javascript - javascript

I need a little help here, so when i add an option from dynamic add select option and click order button it will display the options i picked.
For the next step, i need to count sum of the options i choose. I tried some tips i found earlier, but nothing works.
I have added a disabled input for the sum result. Any suggestion what method i can use here?
Here is the full code:
var data = {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function(option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function () {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function () {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function () {
$('.order').click(function () {
var selectMenu = {};
$("select.type").each(function (i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html("");
$.each(selectMenu, function (index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
})
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:50%">Item name</th>
<th style="width:50%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" disabled> <!-- sum price result here -->
</div>

As you are already using each loop to show your trs you can declare some variable i.e total and then inside each loop just use total += parseInt(data.total) and then show same inside your input .
Demo Code :
var data = {
Food: [{
id: 1,
name: "Fried Rice",
price: 1e4
}, {
id: 2,
name: "Fried Noodle",
price: 9e3
}, {
id: 3,
name: "Pancake",
price: 8500
}, {
id: 4,
name: "French Fries",
price: 7500
}],
Drink: [{
id: 1,
name: "Cola",
price: 4600
}, {
id: 2,
name: "Orange Juice",
price: 5400
}, {
id: 3,
name: "Mineral Water",
price: 3500
}, {
id: 4,
name: "Coffee",
price: 5800
}]
};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function(option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function() {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function() {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function() {
$('.order').click(function() {
var selectMenu = {};
$("select.type").each(function(i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html("");
var total = 0 //decalre this
$.each(selectMenu, function(index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
total += parseInt(data.total); //sum total
})
$(".totalPrice input").val(total) //show inside inputs
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:50%">Item name</th>
<th style="width:50%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" disabled>
<!-- sum price result here -->
</div>

I did not understand your question. But I think you want to sum all the price.
So I have made a little code for you. Hope it will work
let data= {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
let keys = Object.keys(data)
console.log(keys)//["Food", "Drink"]
let price = 0
for (let i = 0; i < keys.length; i++) {
let items = data[keys[i]] //Access the values of the key
for (let j = 0; j < items.length; j++) {
console.log(items[j].price) //10000 ....(in loop)
price = price + items[j].price
}
}
console.log(price)//54300

Related

How to trigger the class and append the content in jquery?

I need to trigger the class "alert success" when the button is clicked in HTML,
The code is:
function appendText() {
var title = $("#title").val();
var content = $("#content").val();
var type = $("#type").val();
var markup = "<div>" + title + content + "</div>";
$(".alert success").append(markup);
$(".closebtn").append()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p style="margin-top: 2%">
<select id="type">
<option value="success">success</option>
<option value="info">info</option>
<option value="warning">warning</option>
<option value="error">error</option>
</select>
<label for="title">title:</label>
<input type="text" value="title" id="title">
<label for="content">content:</label>
<input type="text" id="content" value="content" style="width: 50%">
<button onclick="appendText()">Add Notification</button>
</p>
I need to create dynamically the following HTML code when the button is clicked.
<div class="alert success">
<span class="closebtn">×</span>
<strong>Success!</strong> Indicates a successful or positive action.
</div>
Can you suggest the correct Jquery code for my need?
Here is working and simplified snippet.
Its appending the notification data and also the closebtn close button is working as well and deleting the clicked notification.
Just run snippet to see in action.
function appendText() {
var title = $("#title").val();
var content = $("#content").val();
var type = $("#type").val();
var markup = "<div class='results'><button class='closebtn' onclick='closeAlert(this)'>X</button> " + type + ' ' + title + ' ' + content + "</div>";
if (type === 'success') {
$('.messages').css({
"background-color": "green"
});
} else if (type === 'warning') {
$('.messages').css({
"background-color": "yellow"
});
} else if (type === 'error') {
$('.messages').css({
"background-color": "red"
});
} else if (type === 'info') {
$('.messages').css({
"background-color": "blue"
});
}
$(".messages").html(markup);
}
function closeAlert(_this) {
$(_this).parent().remove()
}
label,
button {
display: block;
}
.results {
display: flex;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p style="margin-top: 2%">
<select id="type">
<option value="success">success</option>
<option value="info">info</option>
<option value="warning">warning</option>
<option value="error">error</option>
</select>
<label for="title">title:</label>
<input type="text" value="title" id="title">
<label for="content">content:</label>
<input type="text" id="content" value="content" style="width: 50%">
<button onclick="appendText()">Add Notification</button>
</p>
<div class="messages"></div>
function appendText() {
var title = $("#title").val();
var content = $("#content").val();
var type = $("#type").val();
var result = '<div>'
+ title + ' ' + content
+ '<div class="alert success">'
+ '<span class="closebtn">×</span>'
+ '<strong>Success!</strong> Indicates a successful or positive action.'
+ '</div>'
+ '</div>';
$('#result').append(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p style="margin-top: 2%">
<select id="type">
<option value="success">success</option>
<option value="info">info</option>
<option value="warning">warning</option>
<option value="error">error</option>
</select>
<label for="title">title:</label>
<input type="text" value="title" id="title">
<label for="content">content:</label>
<input type="text" id="content" value="content" style="width: 50%">
<button onclick="appendText()">Add Notification</button>
</p>
<div id="result"></div>
For HTML Tags or Content
var content = "Hello World";
$(".className").html(content);
Or
var content = "<b>Hello World</b>";
$(".className").html(content);

stuck create table add row dynamically

I create table add row Dynamically but my output be 3 not be 1
is it because of I use div class and not use table(tr & td) ?
example
enter image description here
This is My javascript
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$("#add").on("click", function () {
var newRow = $("div.rounded");
var cols = "";
cols += '<label>Paket </label><input type="text" class="form-control col-md-5" name="paket"><div class="invalid-feedback">Input paket bosz!' + counter + '</div></div>';
cols += '<label>Quantity </label><input type="text" class="form-control col-md-5" name="quantity"><div class="invalid-feedback">Input Quantity!' + counter + '</div></div>';
cols += '<label>Biaya </label><input type="text" class="form-control col-md-5" name="biaya"><div class="invalid-feedback">Input Biaya' + counter + '</div></div>';
newRow.append(cols);
$("div.rounded").append(newRow);
counter++;
});
$("div.rounded").on("click", function (event) {
$(this).closest("form-group").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
</script>
This My View
Paket
Input paket bosz!
<div class="col-4" style="margin-right: -290px;">
<div class="form-group rounded">
<label class="ulang">Quantity </label>
<input type="text" class="form-control col-md-5" name="quantity">
<div class="invalid-feedback">
Input Quantity!
</div>
</div>
</div>
<div class="col-4" style="margin-right: -290px;">
<div class="form-group rounded">
<label class="ulang">Biaya </label>
<input type="text" class="form-control col-md-5" name="biaya">
<div class="invalid-feedback">
Input Biaya
</div>
</div>
<br><br><br> <!-- pembatasan antara add order now -->
</div>

How to get the Sum of Lowest values in 3 rows each added dynamically

The following code will get the lowest value entered in first 3 columns, it is running fine. But after adding the row (Add Row) i am unable to get the lowest value from next 3 columns. Also i want to get the sum of all 3 lowest values from as much columns as user will add. Your kind help is required in this regard.
$(document).ready(function() {
var i = 1;
$("#Add_BDSP").click(function() {
$('#BDSP' + i).html("<td><input type='text' name='QuotedAmount1[" + i + "]' placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount2[" + i + "]'placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount3[" + i + "]' placeholder='Quoted Amount' class='form-control'/></td>");
$('#Tab_BDSP').append('<tr id="BDSP' + (i + 1) + '"></tr>');
i++;
});
$("#Delete_BDSP").click(function() {
if (i > 1) {
$("#BDSP" + (i - 1)).html('');
i--;
}
});
});
var input = $('[name="QuotedAmount1[0]"],[name="QuotedAmount2[0]"],[name="QuotedAmount3[0]"]'),
QuotedAmount1 = $('[name="QuotedAmount1[0]"]'),
QuotedAmount2 = $('[name="QuotedAmount2[0]"]'),
QuotedAmount3 = $('[name="QuotedAmount3[0]"]'),
MulRes = $('[name="ServiceTotalCost"]');
input.change(function() {
var Qoute1 = (isNaN(parseInt(QuotedAmount1.val()))) ? 0 : parseInt(QuotedAmount1.val());
var Qoute2 = (isNaN(parseInt(QuotedAmount2.val()))) ? 0 : parseInt(QuotedAmount2.val());
var Qoute3 = (isNaN(parseInt(QuotedAmount3.val()))) ? 0 : parseInt(QuotedAmount3.val());
MulRes.val(Math.min(Qoute1, Qoute2, Qoute3));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group form-float">
<table class="table table-bordered table-hover" id="Tab_BDSP">
<thead>
<tr>
<td>Amount</td>
</tr>
</thead>
<tbody>
<tr id='BDSP0'>
<td>
<input type="text" name='QuotedAmount1[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount2[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount3[0]' placeholder='Quoted Amount' class="form-control" required />
</td>
</tr>
<tr id='BDSP1'></tr>
</tbody>
</table>
</div>
<a id="Add_BDSP" class="btn btn-default pull-left">Add Row</a><a id='Delete_BDSP' class="pull-right btn btn-default">Delete Row</a>
</div>
<div class="col-md-4">
<div class="input-group form-group">
<span class="input-group-addon">
<i class="material-icons">business_center</i>
</span>
<div class="form-line">
<input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>
</div>
</div>
</div>
But after adding the row (Add Row) i am unable to get the lowest value
from next 3 columns
Your main problem is:
QuotedAmount1 = $('[name="QuotedAmount1[0]"]'),
QuotedAmount2 = $('[name="QuotedAmount2[0]"]'),
QuotedAmount3 = $('[name="QuotedAmount3[0]"]'),
Because you just select QuotedAmount1[0] to QuotedAmount3[0], after you append row new input has QuotedAmount1[1] .. , also you used change and for new row you need to use change with document selector, to get live change. And you should move your variable inside of change event. Important things is, you should select your input without name, here is working snippet:
$(document).ready(function() {
var i = 1;
$("#Add_BDSP").click(function() {
$('#BDSP' + i).html("<td><input type='text' name='QuotedAmount1[" + i + "]' placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount2[" + i + "]'placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount3[" + i + "]' placeholder='Quoted Amount' class='form-control'/></td>");
$('#Tab_BDSP').append('<tr id="BDSP' + (i + 1) + '"></tr>');
i++;
});
$("#Delete_BDSP").click(function() {
if (i > 1) {
$("#BDSP" + (i - 1)).html('');
i--;
}
});
});
$(document).on('change', '#Tab_BDSP tbody tr td input[type="text"]', function() {
let result = 0;
var MulRes = $('input#ServiceTotalCost');
var QuotedAmount1 = $(this).parent().find('input[type="text"]').eq(0),
QuotedAmount2 = $(this).parent().find('input[type="text"]').eq(1),
QuotedAmount3 = $(this).parent().find('input[type="text"]').eq(2);
var Qoute1 = (isNaN(parseInt(QuotedAmount1.val()))) ? 0 : parseInt(QuotedAmount1.val()),
Qoute2 = (isNaN(parseInt(QuotedAmount2.val()))) ? 0 : parseInt(QuotedAmount2.val()),
Qoute3 = (isNaN(parseInt(QuotedAmount3.val()))) ? 0 : parseInt(QuotedAmount3.val());
var min = Math.min(Qoute1, Qoute2, Qoute3);
$(this).parent().attr('data-lowest', min)
$('#Tab_BDSP tbody tr td').each(function() {
result += +$(this).attr('data-lowest')
});
MulRes.val(result)
});
Thank you for kind response,
the code is running perfect,
but the issue is if i change the value in additional rows,
it adds the lowest into the sum,
e.g. 1st row have 300000 400000 500000 and second row have 600000 700000 800000 The total sum will be 900000 which is perfect. but if i change the value from 600000 to 200000 it should shows 700000 but it gives value of 1100000. Your kind help is needed to rectify this issue in the given code. – ADIL I.T 8 mins ago
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group form-float">
<table class="table table-bordered table-hover" id="Tab_BDSP">
<thead>
<tr>
<td>Amount</td>
</tr>
</thead>
<tbody>
<tr id='BDSP0'>
<td>
<input type="text" name='QuotedAmount1[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount2[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount3[0]' placeholder='Quoted Amount' class="form-control" required />
</td>
</tr>
<tr id='BDSP1'></tr>
</tbody>
</table>
</div>
<a id="Add_BDSP" class="btn btn-default pull-left">Add Row</a><a id='Delete_BDSP' class="pull-right btn btn-default">Delete Row</a>
</div>
<div class="col-md-4">
<div class="input-group form-group">
<span class="input-group-addon">
<i class="material-icons">business_center</i>
</span>
<div class="form-line">
<input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>
</div>
</div>
</div>
Also i want to get the sum of all 3 lowest values from as much columns
as user will add
For get sum you need to get min and also old lowest value
This code works. I just made all of the script run separately so it worked.
$(".input0").keyup(function() {
var val10 = $("[name='a1[0]']").val();
var val20 = $("[name='a2[0]']").val();
var val30 = $("[name='a3[0]']").val();
var lowestValue0 = Math.min(val10, val20, val30);
$("[name='answer[0]']").val(lowestValue0);
$("[name='total']").val(lowestValue0);
});
$(document).keyup(function() {
var sum = "";
$('.inputClass').each(function() {
sum += this.value;
});
$("[name='total']").val(sum);
});
$(document).ready(function() {
var a = "1";
$(".add").click(function() {
$('<div class="valueDiv' + a + '"><input name="a1[' + a + ']" class="input' + a + '" placeholder="Value 1"><input name="a2[' + a + ']" class="input' + a + '" placeholder="Value 2"><input name="a3[' + a + ']" class="input' + a + '" placeholder="Value 3"><br><h5>Lowest Value = <\/h5><input name="answer[' + a + ']" class="inputClass" readonly placeholder="Lowest Value"><hr><\/div>').appendTo("#mainDiv");
$('#scripts').append('<script type="text/javascript" id="script' + a + '">$(".input' + a + '").keyup(function() { var val1' + a + ' = $("[name=\'a1[' + a + ']\']").val(); var val2' + a + ' = $("[name=\'a2[' + a + ']\']").val(); var val3' + a + ' = $("[name=\'a3[' + a + ']\']").val(); var lowestValue' + a + ' = Math.min(val1' + a + ', val2' + a + ', val3' + a + '); $("[name=\'answer[' + a + ']\']").val(lowestValue' + a + '); });<\/script>');
a++;
});
$(".delete").click(function() {
if (a > 1) {
$(".valueDiv" + (a - 1)).remove();
$("script" + (a - 1)).remove();
a--;
}
var sum = "";
$('.inputClass').each(function() {
sum += this.value;
});
$("[name='total']").val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div id="mainDiv" style="width: 100%; height: 100%; padding: 50px;">
<div class="valueDiv0">
<hr>
<input name="a1[0]" class="input0" placeholder="Value 1">
<input name="a2[0]" class="input0" placeholder="Value 2">
<input name="a3[0]" class="input0" placeholder="Value 3">
<br>
<h5>Lowest Value = </h5>
<input name="answer[0]" class="inputClass" readonly placeholder="Lowest Value">
<hr>
</div>
</div>
<div style="width: 100%; height: 100%; padding: 0px 50px;">
<h5>Sum of All Lowest Values</h5>
<input style="width: 230px;" name="total" readonly placeholder="Total Value of All Lowest Values">
</div>
<div id="scripts">
</div>
<br>
<div>
<button class="btn btn-primary add">Add Row</button>
<button class="btn btn-danger delete">Delete Row</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

How to display the result in another page after submit?

How can I display my data into another html after submit? I tried to store the value in local Storage and that didn't work out. How can i display the result in other page? In the below snippet i some how achieved to display data by using show and hide methods. But i'm looking to display my data in new HTML page.
var data = [
{
"username": "MADHU BABU POOJALA",
"skills": "BD",
"location": "Hyderabad",
"email": "rgw#yahoo.in",
"bscore": 856,
"ranking": 14652,
},
{
"username": "Mj",
"skills": ".net",
"location": "Hyderabad",
"email": "csaca#yahoo.in",
"bscore": 8540,
"ranking": 1452,
}
];
var result = [];
function Sort(val) {
result.sort(function (a, b) {
if (a[val] < b[val]) return -1;
if (a[val] > b[val]) return 1;
return 0;
});
searchResult(result);
}
function search(str) {
var str = str.trim().toUpperCase();
if (str !== '') {
var rslt = [];
for (var j = 0; j < result.length; j++) {
if (result[j].skills.toUpperCase().match(str)) {
rslt.push(result[j]);
}
}
searchResult(rslt);
} else {
searchResult(result);
}
}
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '',
location = $("#location").val() || '',
i;
result = []
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]
["email"].toUpperCase() === email.toUpperCase()) || (data[i]["location"].toUpperCase() ===
location.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
$(".ip").hide();
$(".tb").show();
var output = getResult();
searchResult(output);
});
$("#back").click(function () {
$('input[type="text"]').val('').removeAttr('checked').removeAttr('selected');
$('input[type="email"]').val('').removeAttr('checked').removeAttr('selected');
$(".tb").hide();
$(".ip").show();
});
function searchResult(output) {
var html = '';
$.each(output, function (key, value) {
html += '<div style="border:1px solid #000;padding:10px;margin:10px;">';
html += '<span style="font-weight:bold;">' + value.username + '</span>' +
'<br/>';
html += '<span>' + 'Email :' + '</span>' + '<span>' + value.email + '</span>' +
'<br/>';
html += '<span>' + 'Skills :' + '</span>' + '<span>' + value.skills + '</span>' +
'<br/>';
html += '<span>' + 'Location :' + '</span>' + '<span>' + value.location + '</span>' +
'<br/>';
html += '<span>' + 'B-score :' + '</span>' + '<span>' + value.bscore + '</span>' +
'<br/>';
html += '<span>' + 'Ranking :' + '</span>' + '<span>' + value.ranking + '</span>' +
'<br/>';
html += '</div>';
});
$('#table').html(html);
}
$(document).ready(function () {
$('#submit').attr('disabled', 'disabled');
$('input[type="text"]').keyup(function () {
if ($(this).val() != '') {
$('input[type="submit"]').removeAttr('disabled');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU"
crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
.results tr[visible='false'],
.no-result {
display: none;
}
.results tr[visible='true'] {
display: table-row;
}
.form-group {
position: fixed;
top: 30%;
left: 50%;
width: 1200px;
height: 200px;
background: #fff;
transform: translate(-15%, -50%);
}
</style>
</head>
<body>
<div class="ip">
<div class="form-group ">
<div class="col-4">
<label for="skills">Skills</label>
<input class="form-control" id="skills" type="text" placeholder="skills">
</div>
<div class="col-4">
<label for="email">Email</label>
<input class="form-control" id="email" type="text" placeholder="mail id">
</div>
<div class="col-4">
<label for="username">Username</label>
<input class="form-control" id="username" type="text" placeholder="username">
</div>
<div class="col-4">
<label for="location">location</label>
<input class="form-control" id="location" type="text" placeholder="location">
</div>
<br>
<div class="col-4">
<input id="submit" class="btn" type="submit" value="submit" disabled='disabled'>
</div>
</div>
</div>
<br>
<div style="display: none" class="tb">
<button class="btn" id="back">back to search</button>
<br>
<br>
<br>
<div class="container-fluid">
<div class="row">
<div class="left">
<label style="font-size: 20px;color: black;margin:0px">
Core Skills :
</label>
<input type="text" onkeyup="search(this.value)">
</div>
<div class="right">
<form>
<label style="font-size: 20px;color: black;margin:0px">
Sort By :
</label>
<select onchange="Sort(this.value)">
<option>-- select --</option>
<option value="username">A to Z</option>
<option value="bscore">B-score</option>
<option value="ranking">Ranking</option>
</select>
</form>
</div>
</div>
</div>
<div id="table">
</div>
</div>
</body>
</html>

I can't seem to get my code to work

I want to create a coffee shop transaction form. I've tried everything i know. but still nothing. this is a test design I have here the Item Name and Item Size. Each item will have different prices, example: Item X (size a = 5, size b = 10, size c = 15), Item Y (size a = 6, size b = 11, size c = 12)... then a quantity will be entered, after clicking the "ADD ITEM" button, the sub Total(not sure) should appear on the boxes on the left.
how should i make this work? thanks.
PS: sorry if you find it hard to understand what i say. thanks tho!
just to add, i used the sizes offered by star bucks.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" >
<link rel="stylesheet" type="text/css" href="sbwadcss.css">
<script type="text/javascript">
var TotalPrice=0;
function chooseItem()
{
var itemPrice = parseInt(0);
var itemName = document.getElementById('itemName').value;
var itemSize = document.getElementById('itemSize').value;
var qty = document.getElementById('QuanVal').value.trim();
var subTotal = document.getElementById('subTotal').value;
if (qty!="")
{
if (qty.match(/^[0-9]+$/))
{
if(itemName=="Caffe Latte")
{
if(itemSize=="Tall")
itemPrice = (75*qty);
else if(itemSize=="Grande")
itemPrice = (105*qty);
else(itemSize=="Venti")
itemPrice = (135*qty);
}
if(itemName=="Caffe Americano")
{
if(itemSize=="Tall")
itemPrice = (80*qty);
else if(itemSize=="Grande")
itemPrice = (100*qty);
else(itemSize=="Venti")
itemPrice = (120*qty);
}
if(itemName=="Cappuccino")
{
if(itemSize=="Tall")
itemPrice = (70*qty);
else if(itemSize=="Grande")
itemPrice = (95*qty);
else(itemSize=="Venti")
itemPrice = (120*qty);
}
if(itemName=="Espresso")
{
if(itemSize=="Tall")
itemPrice = (85*qty);
else if(itemSize=="Grande")
itemPrice = (105*qty);
else(itemSize=="Venti")
itemPrice = (125*qty);
}
if(itemName=="Flat White")
{
if(itemSize=="Tall")
itemPrice = (75*qty);
else if(itemSize=="Grande")
itemPrice = (100*qty);
else(itemSize=="Venti")
itemPrice = (125*qty);
}
}
document.getElementById("subTotal").value = itemPrice;
TotalPrice+=itemPrice;
if(itemName=="Caffe Latte")
{
document.getElementById('itemName').value += "\n" + "Caffe Latte" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else if(itemName=="Caffe Americano")
{
document.getElementById('itemName').value += "\n" + "Caffe Americano" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else if(itemName=="Cappuccino")
{
document.getElementById('itemName').value += "\n" + "Cappuccino" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else if(itemName=="Espresso")
{
document.getElementById('itemName').value += "\n" + "Espresso" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else
{
document.getElementById('itemName').value += "\n" + "Flat White" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
}
else
alert("Invalid Quantity!!");
}
else
alert("Please Enter Quantity!!");
function Payment()
{
var payment = document.getElementById('paymnet').value.trim();
var TotalPrice = document.getElementById('TotalPrice').value;
if (payment !="")
{
if (payment.match(/^[0-9]+$/))
{
if (TotalPrice < payment)
{
var change = payment - TotalPrice;
document.getElementById('change').value= "Php" + change + ".00";
TotalPrice=0;
}
else
alert("Invalid Amount Entered!!");
}
else
alert("Invalid Amount Entered!!");
}
else
alert("Please Entered!!");
}
function NewTransaction(targ1,targ2,targ3)
{
var OK = confirm("Are you sure you want to make New Transaction? \n OK or CANCEL? ");
if (OK==true)
targ1.value="";
targ2.value="";
targ3.value="";
TotalPrice=0;
document.getElementById('itemName').value ="";
document.getElementById('price').value ="";
document.getElementById('qty').value ="";
document.getElementById('TotalPrice').value ="";
document.getElementById('payment').value="";
document.getElementById('change').value="";
}
</head>
<body>
<div id="form">
<legend class="wrap"><h3>COFFEE SHOP!</h3></legend>
<h4>TRANSACTION FORM</h4>
<div class="content">
<div class="left">
Item Name:
</div>
<div class="right">
<select id="itemName">
<option selected disabled="disabled">SELECT ITEM</option>
<option>Caffe Latte</option>
<option>Caffe Americano</option>
<option>Cappuccino</option>
<option>Espresso</option>
<option>Flat White</option>
</select>
</div>
</div>
<div class="content">
<div class="left">
Item Size:
</div>
<div class="right">
<select id="itemSize">
<option selected disabled="disabled">SELECT SIZE</option>
<option>Tall</option>
<option>Grande</option>
<option>Venti</option>
</select>
</div>
</div>
<div class="content">
<div class="left">
Quantity:
</div>
<div class="right">
<input type="text" id="QuanVal">
</div>
</div>
<div class="content">
<div class="left">
Price:
</div>
<div class="right">
<input type="text" id="subTotal" disabled="disabled">
</div>
</div>
<div class="btnContent">
<input type="button" value="ADD ITEM" onclick="AddItem()" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
<div class="btnContent">
<input type="button" value="NEW TRANSACTION" onclick="NewTransaction(document.getElementById('itemName'),document.getElementById('QuanVal'),document.getElementById('subTotal'))" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
</div>
<div id="form2">
<div class="content">
<div class="inline-div">
<p align="center">Item Name</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="itemName" disabled="disable"></textarea>
</div>
<div class="inline-div">
<p align="center">Price</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="price" disabled="disable"></textarea>
</div>
<div class="inline-div">
<p align="center">Quantity</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="qty" disabled="disable"></textarea>
</div>
</div>
<div class="btnContent" style="width: 180px; padding-top: 5px;">
TOTAL PRICE:
<input type="text" id="TotalPrice" disabled="disabled">
</div>
<div class="btnContent" style="width: 180px; padding-left: 18px; padding-top: 5px;">
ENTER PAYMENT:
<input type="text" id="payment">
<input type="button" value="SUBMIT PAYMENT" onclick="Payment()" style="background-color: grey; margin:3px; border-radius: 5px;">
CHANGE :
<input type="text" id="change" disabled="disabled">
</div>
</div>
</body>
</html>
Maybe you use an object for the product's prices.
Changes:
using small variable and function names
id for collections
some other id
using an object for propducts and their size
exit early principle for checking requirements
collections does not show an empty line in advance
keeping totalPrice while payment
complete reseting all inputs in newTransaction
newTransaction without parameters
var totalPrice = 0,
products = {
"Caffe Latte": {
Tall: 75,
Grande: 105,
Venti: 135
},
"Caffe Americano": {
Tall: 80,
Grande: 100,
Venti: 120
},
Cappuccino: {
Tall: 70,
Grande: 95,
Venti: 120
},
Espresso: {
Tall: 85,
Grande: 105,
Venti: 125
},
"Flat White": {
Tall: 75,
Grande: 100,
Venti: 125
}
};
function addItem() {
var itemPrice,
itemName = document.getElementById('itemName').value,
itemSize = document.getElementById('itemSize').value,
quantity = document.getElementById('quantity').value.trim(),
subTotal = document.getElementById('subTotal').value;
if (!products[itemName]) {
alert("Please Enter Item Name!");
return;
}
if (!(itemSize in products[itemName])) {
alert("Please Enter Item Site!");
return;
}
if (quantity === "") {
alert("Please Enter Quantity!");
return;
}
if (!quantity.match(/^[0-9]+$/)) {
alert("Invalid Quantity!!");
return;
}
itemPrice = quantity * products[itemName][itemSize];
totalPrice += itemPrice;
document.getElementById("subTotal").value = itemPrice;
document.getElementById('collectionItemName').value += itemName + "\n";
document.getElementById('collectionPrice').value += products[itemName][itemSize] + "\n";
document.getElementById('collectionQuantity').value += quantity + "\n";
document.getElementById('totalPrice').value = totalPrice;
}
function payment() {
var payment = document.getElementById('payment').value.trim(),
change;
if (!payment) {
alert("Please Enter Payment!");
return;
}
if (!payment.match(/^\d+$/)) {
alert("Invalid Amount Entered!");
return;
}
if (totalPrice > payment) {
alert("Payment is not enough!");
return;
}
change = payment - totalPrice;
document.getElementById('change').value = "Php" + change + ".00";
}
function newTransaction() {
var ok = confirm("Are you sure you want to make New Transaction? \n OK or CANCEL? ");
if (ok) {
totalPrice = 0;
document.getElementById('itemName').selectedIndex = 0;
document.getElementById('itemSize').selectedIndex = 0;
document.getElementById('subTotal').value = "";
document.getElementById('quantity').value = "";
document.getElementById("subTotal").value = "";
document.getElementById('collectionItemName').value = "";
document.getElementById('collectionPrice').value = "";
document.getElementById('collectionQuantity').value = "";
document.getElementById('totalPrice').value = "";
document.getElementById('payment').value = "";
document.getElementById('change').value = "";
}
}
<div id="form">
<h3>COFFEE SHOP!</h3>
<h4>TRANSACTION FORM</h4>
<div class="content">
<div class="left">Item Name:</div>
<div class="right">
<select id="itemName">
<option selected disabled="disabled">SELECT ITEM</option>
<option>Caffe Latte</option>
<option>Caffe Americano</option>
<option>Cappuccino</option>
<option>Espresso</option>
<option>Flat White</option>
</select>
</div>
</div>
<div class="content">
<div class="left">Item Size:</div>
<div class="right">
<select id="itemSize">
<option selected disabled="disabled">SELECT SIZE</option>
<option>Tall</option>
<option>Grande</option>
<option>Venti</option>
</select>
</div>
</div>
<div class="content">
<div class="left">Quantity:</div>
<div class="right"><input type="text" id="quantity"></div>
</div>
<div class="content">
<div class="left">Price:</div>
<div class="right"><input type="text" id="subTotal" disabled="disabled"></div>
</div>
<div class="btnContent">
<input type="button" value="ADD ITEM" onclick="addItem()" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
<div class="btnContent">
<input type="button" value="NEW TRANSACTION" onclick="newTransaction()" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
</div>
<div id="form2">
<div class="content">
<div class="inline-div">
<p align="center">Item Name</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="collectionItemName" disabled="disabled"></textarea>
</div>
<div class="inline-div">
<p align="center">Price</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="collectionPrice" disabled="disabled"></textarea>
</div>
<div class="inline-div">
<p align="center">Quantity</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="collectionQuantity" disabled="disabled"></textarea>
</div>
</div>
<div class="btnContent" style="width: 180px; padding-top: 5px;">
TOTAL PRICE:
<input type="text" id="totalPrice" disabled="disabled">
</div>
<div class="btnContent" style="width: 180px; padding-left: 18px; padding-top: 5px;">
ENTER PAYMENT:
<input type="text" id="payment">
<input type="button" value="SUBMIT PAYMENT" onclick="payment()" style="background-color: grey; margin:3px; border-radius: 5px;">
CHANGE :
<input type="text" id="change" disabled="disabled">
</div>
</div>

Categories