Total required in javascript - javascript

I have a query in javascript.. Please check the below image
In Above image :
First Input Box is Description
2nd Input Box is Qty
3rd is Value
I have got total qty using below script onchange of textbox :
function findTotal(){
var total = 0;
var $changeInputs = $('input.qtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
$("#totalvval").val(total);
}
I have got total Value using below :
function qfindTotal(){
var total = 0;
var $changeInputs = $('input.qqtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.qtotal').text(total);
$("#totalqval").val(total);
if(total>10000){
alert("Amount should not be greater than 10000");
}
}
My query is that we need total of qty x value + qty x value + qty x value =total

You can try something like this:
Fiddle
Code
function createHTML() {
var html = "";
for (var i = 0; i < 3; i++) {
html += "<input type='text' class='qty' id='txtQty_" + i + "' onblur='updateTotal()' />";
html += "<input type='text' class='cost' id='txtQty_" + i + "' onblur='updateTotal()'/>";
html += "<br/>"
}
html += "Qty Total: <span id='qty_total'>0</span>";
html += "Cost Total: <span id='cost_total'>0</span>";
document.getElementById("content").innerHTML = html
}
function updateTotal() {
var qty = document.getElementsByClassName("qty");
var cost = document.getElementsByClassName("cost");
var total_qty = 0;
var total_cost = 0;
for (var i = 0; i < qty.length; i++) {
if (qty[i].value && cost[i].value) {
total_cost += qty[i].value * cost[i].value;
total_qty += parseInt(qty[i].value);
}
}
document.getElementById("qty_total").innerHTML = total_qty;
document.getElementById("cost_total").innerHTML = total_cost;
}
(function() {
createHTML();
})()
<div id="content"></div>

Related

How can I change the value of initialValue after each run?

I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;
this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br>
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src="java.js"></script>
<script>
var tblResult = document.getElementById("tblResult");
var personList = [];
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById("persistedResult").value);
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
//constructor function
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;
this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}
//javascript in the body tag
var tblResult = document.getElementById("tblResult");
var personList = [];
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById("persistedResult").value);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br> //rdo for Add
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br> //rdo for Subs
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
</body>
</html>
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
function printResult() {
var display = "";
var initialValue = 10000;
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
display = "<tr>";
display += "<td>" + (personList[i].addNum()) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
display = "<tr>";
display += "<td>" + (personList[i].minusNum()) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
}
//Constructor Function
function Compute(initialNum, numOne) {
this._initialNum = initialNum;
this._numOne = numOne;
this.addNum = function() {
this._initialNum += this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum -= this._numOne;
return this._initialNum;
};
}
Since HTTP is stateless and you want to perform operations on 2 different actions, you will need to store the result of each action in some place. For the simplest example, you can create hidden field on your HTML page. This can have value of 10000 when your HTML is loaded for the first time and update it’s value after each action is executed.
Let’s assume you have following hidden field on your HTML:
<input type=“hidden” id=“persistedResult” value=“10000” />
Here is your updated printResult method:
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById(‘persistedResult’).value);
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById(‘persistedResult’).value = newValue;
}
Note: This is a primitive example to guide you how to achieve data persistence. Generally, the data will be persisted on server.
This code takes care of scenario where there is only one person in the list, which is the approach in your current code example. You will need to enhance the logic if you want to have this working on an array of persons.
var valueEl = document.getElementById('value');
var addEl = document.getElementById('add');
var resultEl = document.getElementById('result');
var calculateEl = document.getElementById('calculate');
var initialValue = 1000;
function appendResult(result) {
var liEl = document.createElement("li");
liEl.innerHTML = result;
resultEl.appendChild(liEl);
}
function handleClickCalculate() {
var operand = addEl.checked ? 1 : -1;
var value = +valueEl.value * operand;
initialValue += value
appendResult(initialValue);
}
calculateEl.addEventListener('click', handleClickCalculate)
appendResult(initialValue);
jsFiddle

How can I use jQuery to randomly select one column from each row?

I have dynamically created rows and columns with jQuery. Can anyone help me on how to select a random column from each row? So far here is how my code looks like;
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
})
You can use a comibnation of Math.floor() and Math.random() to get an integer between 1 and the amount of columns (x) per row.
Math.floor (Math.random () * x) + 1
I simplified your given example and added a funtion to select one random column per row. For this example I dynamically add a class for each selected column.
$(document).ready (function () {
var rows = 7;
var cols = 10;
var gameHolder = '';
for (var i = 0; i < rows; i++) {
gameHolder += '<div class="row">';
for(var j = 0; j < cols; j++)
gameHolder += '<div class="col"></div>';
gameHolder += '</div>';
}
$("#board").html(gameHolder);
})
function select_cols () {
var canvas = $("#board");
//reset all columns
$('.col').removeClass ('selected');
//loop through every row
canvas.find ('.row').each (function (i) {
//count columns and select random one
var count = $(this).find ('.col').size (); // $(this) is the current row
var selected = Math.floor (Math.random () * count) + 1;
//get your selected column-element
var column = $(this).find ('.col:nth-child(' + selected + ')') // :nth-child(x) is a css-selector
//do something with it. for example add a class
column.addClass ('selected');
});
}
#board {
border: 1px solid #999;
}
.row {
display: flex;
}
.col {
flex-grow: 1;
height: 10px;
border: 1px solid #999;
}
.selected {
background-color: #958;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board"></div>
<br>
<button onclick="select_cols ();">select random columns</button>
I see that you're asking for a random column for each row, but if you'd like just a random position on the game board, you could do something like this:
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col' id='" + i + "-" + j + "'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
function selectRandomLocation(){
var pos = $('#' + Math.floor(Math.random() * rows) + '-' + Math.floor(Math.random() * cols));
return pos;
}
})
you can use foreach and random ,
try :
var j = 0;
$("row").each(function(){
random_col = Math.floor(Math.random() * 10);
var i = 0;
$("li").each(function(){
if(random_col == i)
/* $(this) = your random col */
alert("the random col is a number "+i+" for col number "+j);
i++;
});
j++;
});

How to get the Same price for grouped items

This code works perfect for Items that have the same address.
If they have same addressId, then they are grouped together under that one address.
5 items same address that shows up fine, but it is placing the same shipping fee for each item.
Need to only show the same as address, only one shipping fee for Same Group of items.
Please help, I have been trying at this for past two-days..Cannot figure out how to return the one shipping fee for group of items.
var itemshippingGroup, should be grouped shipping fee, display, only one of those fees, not each 5-items as separate fee.
See code below
//cart rows
var numofItems = productCart.length;
var productSubTotal = 0, shipping = 0;
var retriveAdd = getStoredData(address_cookie_name);
//alert(retriveAdd);
var productAddress = $.parseJSON(retriveAdd);
var k = 0;
for(var ad in productAddress){
var j = 0;
for(var i in productCart) {
var ship = 0;
var value = productCart[i];
var addressId = productCart[i].addressId;
var shippingId = parseFloat(productCart[i].shippingmethod).toFixed(2);
if(ad == addressId){
var item = parseInt(i)+1;
var address = productAddress[productCart[i].addressId];
var itemshipping = parseFloat(productCart[i].shippingmethod).toFixed(2);
var fName = '', lName = '';
if(address){
fName = address.firstName;
lName = address.lastName;
itemAddress = address.address1+" <br> "+ address.city+","+address.state+" "+address.zipcode;
if(addressId == shippingId){
var itemshippingGroup = shippingId;
}
}
// Sub Total
productSubTotal = productSubTotal + ((parseFloat(value.productPrice) + parseFloat(value.productTax)) * value.productQty);
var trStyle = "style='background-color:#FFFFFF;'";
if(k%2 == 0){
trStyle = "style='background-color:#F1F1F1;'";
}
cart_html += '<tr id="cart_row_'+i+'" class="cart_row" '+trStyle+'>';
cart_html += '<td class="confirm-product"><span class="clearfix first_item last_item"><img src="'+value.productImage+'" alt="" title="'+value.productName+'" class="cart-images"></td>';
cart_html += '<td>'+value.productName+'<br>'+fName+' '+lName+'</td>';
if(j == 0){
cart_html += '<td>'+itemAddress+'</td>';
}else{
cart_html += '<td> </td>';
}
j++;
cart_html += '<td>'+currencySymbol+''+parseFloat(value.productPrice).toFixed(2)+'</td>';
cart_html += '<td>'+currencySymbol+''+parseFloat(value.productTax)+'</td>';
cart_html += '<td class="itemshipping">'+currencySymbol+' '+itemshipping+'</td>';
//cart_html += '<td>'+currencySymbol+' '+itemshipping+'</td>';
cart_html += '<td>'+currencySymbol+' '+ ((parseFloat(value.productPrice) + parseFloat(value.productTax))*value.productQty).toFixed(2)+'</td>';
//cart_html += '<td>×</td>';
cart_html += '</tr>';
checkButton(value.uProductID);
total_items += value.productQty;
shipping += parseFloat(productCart[i].shippingmethod);
}
}
k++;
}

Display the checkboxes selected into a section and the unselected into another one

I want to show the checkboxes selected into a div but actually I have a duplicate item in the list and I'm not sure how to display the unselected items into another div.
You can try out here http://jsfiddle.net/tedjimenez/7wzR5/
Here my code:
JS CODE
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var html = "";
/* Array will be converted to an ul list */
for (var i = 0; i < list.length; i++) {
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").append(html);
THE HTML CODE
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Function to display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "<li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
Simply add another div after selectionResult like this:
<div id="unselectedResult"></div>
And then update showBoxes() with the following code:
function showBoxes(frm) {
var checkedItems = "Checked:<br>\n";
var uncheckedItems = "Unchecked:<br>\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
else {
uncheckedItems = uncheckedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
$('#unselectedResult').append(uncheckedItems);
}
Should get the result you're looking for.
This should work. Added another array listChecked to track checked values.
<script>
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var listChecked = new Array();
$(document).ready(function() {
displayUnchecked();
});
/* Array will be converted to an ul list */
function displayUnchecked()
{
var html = "";
for (var i = 0; i < list.length; i++) {
if ($.inArray(list[i], listChecked) == -1)
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").html(html);
}
</script>
</head>
<body>
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//alert('here');
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
listChecked.push(frm.boxvalue[i].value);
}
}
$.each(listChecked, function (index, value)
{
checkedItems = checkedItems + "<li>" + value + "</li>";
});
//alert('here');
displayUnchecked();
//$("#elmAv").empty();
$("#selectionResult").html(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
</body>

How to read value of Textbox which is inside table

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

Categories

Resources