Javascript set value of input field not lasting - javascript

Working on a blackjack game for a class and having some trouble with the display function. It does change the value of the field but then it reverts back after the function is done. How do I make the change last?
<html>
<head>
<script type="text/javascript">
function stack()
{
this.cards = new Array();
this.makeDeck = buildDeck;
this.deal = dealCard;
this.add = addCard;
}
function dealCard()
{
return this.cards.shift();
}
function addCard(card)
{
this.cards.push(card);
}
function buildDeck()
{
var ranks = new Array("Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King");
var suits = new Array("Clubs", "Diamonds", "Hearts", "Spades");
this.cards = new Array(52);
for (s = 0; s < suits.length; s++)
{
for (r = 0; r < ranks.length; r++)
{
this.cards[(s * ranks.length) + r] = new card(ranks[r], suits[s]);
}
}
}
function card(r, s)
{
this.rank = r;
this.suit = s;
}
function display()
{
document.getElementById("player_card_1").value = "anything";
alert("here");
}
function newGame()
{
var Player = new stack();
var Dealer = new stack();
var Deck = new stack();
Deck.makeDeck();
Player.add(Deck.deal());
display();
}
</script>
<style type="text/css">
input {
background:transparent
}
</style>
</head>
<body>
<table bgcolor="#33CC33">
<tr>
<td style="font:14pt bold">Your cards</td>
<td></td>
<td style="font:14pt bold">Dealer's cards</td>
<td></td>
</tr>
<tr>
<td><input type="text" readonly="readonly" value="" id="player_card_1"></td>
<td><input type="text" readonly="readonly" value="" id="p_card_1_val"></td>
<td><input type="password" readonly="readonly" value="" id="dealer_card_1"></td>
<td><input type="password" readonly="readonly" value="" id="d_card_1_val"></td>
</tr>
<tr>
<td><input type="text" readonly="readonly" value="" id="player_card_2"></td>
<td><input type="text" readonly="readonly" value="" id="p_card_2_val"></td>
<td><input type="text" readonly="readonly" value="" id="dealer_card_2"></td>
<td><input type="text" readonly="readonly" value="" id="d_card_2_val"></td>
</tr>
<tr>
<td><input type="text" readonly="readonly" value="" id="player_card_3"></td>
<td><input type="text" readonly="readonly" value="" id="p_card_3_val"></td>
<td><input type="text" readonly="readonly" value="" id="dealer_card_3"></td>
<td><input type="text" readonly="readonly" value="" id="d_card_3_val"></td>
</tr>
<tr>
<td><input type="text" readonly="readonly" value="" id="player_card_4"></td>
<td><input type="text" readonly="readonly" value="" id="p_card_4_val"></td>
<td><input type="text" readonly="readonly" value="" id="dealer_card_4"></td>
<td><input type="text" readonly="readonly" value="" id="d_card_4_val"></td>
</tr>
<tr>
<td><input type="text" readonly="readonly" value="" id="player_card_5"></td>
<td><input type="text" readonly="readonly" value="" id="p_card_5_val"></td>
<td><input type="text" readonly="readonly" value="" id="dealer_card_5"></td>
<td><input type="text" readonly="readonly" value="" id="d_card_5_val"></td>
</tr>
<tr>
<td><input type="text" readonly="readonly" value="Total"></td>
<td><input type="text" readonly="readonly" value=""></td>
<td><input type="text" readonly="readonly" value="Total"></td>
<td><input type="text" readonly="readonly" value=""></td>
</tr>
</table>
<br>
<form name="buttons" action="">
<button name="deal" onclick="newGame()">Deal</button>
<button name="hit">Hit</button>
<button name="stand">Stand</button>
</form>
</body>
</html>

Try this code. Replace your form code with
<form name="buttons" action="">
<input type="button" name="deal" onclick="newGame()"/>Deal
<input type="button" name="hit">Hit</button>
<input type="button" name="stand">Stand</button>
</form>

Related

How to add multiple text boxes of currency using JavaScript when one could be empty?

I am attempting to build a form that only adds boxes together when the input is not empty. Thus far, I can get the form to work when at least two boxes are not empty. However, I can not seem to get the form to work when only one box has a value present.
I have tried adding an additional line to the code as follows:
else if (debit1 != "") {
totalDebit = parseFloat(debit1);
document.getElementById("debitTotal").value = totalDebit.toFixed(2);
}
However, this does not appear to work.
For some detail, I would still consider myself inexperienced with JavaScript, having only used it for form validation in the past. These validations mostly dealt with just required text boxes or drop down boxes so relatively simple things. I realize that a loop may be a better way to go about achieving these results but I am not yet familiar enough with those to attempt on my own.
CSS:
<style>
.Header
{
border: solid black 1px;
background-color: #a9e6fc;
padding: 5px;
text-align: center;
}
table
{
border-collapse: separate;
width: 100%;
border: 1px solid black;
}
table.ex1
{
table-layout: auto;
}
.actionButtons
{
border: solid black 1px;
padding: 5px;
overflow: auto;
background-color: #ff5b5b;
}
.submitButton
{
font-size: 16px;
float: left;
}
.cancelButton
{
font-size: 16px;
float: right;
}
</style>
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>GL Ticket</title>
</head>
<body>
<form name="myForm" method="post">
<table>
<tr>
<td>Account:</td><td>DEBIT</td><td>CREDIT</td><td>T/C</td><td>DATE</td><td>CHECK #</td><td>SPECIFIC G/L DESCRIPTION</td>
</tr>
<td><input type="text" id="OBKey__51_1" name="OBKey__51_1" size="15" maxlength="10"></td>
<td><input type="text" id="debit1" name="debit1" size="15" maxlength="10"></td>
<td></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
<tr>
<td><input type="text" id="OBKey__51_2" name="OBKey__51_2" size="15" maxlength="10"></td>
<td></td>
<td><input type="text" id="credit1" name="credit1" size="15" maxlength="10"></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
</tr>
<tr>
<td><input type="text" id="OBKey__51_3" name="OBKey__51_3" size="15" maxlength="10"></td>
<td><input type="text" id="debit2" name="debit2" size="15" maxlength="10" onblur="calculateDebits()"></td>
<td></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
</tr>
<tr>
<td><input type="text" id="OBKey__51_4" name="OBKey__51_4" size="15" maxlength="10"></td>
<td></td>
<td><input type="text" id="credit2" name="credit2" size="15" maxlength="10" onblur="calculateCredits()"></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
</tr>
<tr>
<td><input type="text" id="OBKey__51_5" name="OBKey__51_5" size="15" maxlength="10"></td>
<td><input type="text" id="debit3" name="debit3" size="15" maxlength="10" onblur="calculateDebits()"></td>
<td></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
</tr>
<tr>
<td><input type="text" id="OBKey__51_6" name="OBKey__51_6" size="15" maxlength="10"></td>
<td></td>
<td><input type="text" id="credit3" name="credit3" size="15" maxlength="10" onblur="calculateCredits()"></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
<td></td>
</tr>
<tr>
<td><input type="text" id="OBKey__51_7" name="OBKey__51_7" size="15" maxlength="10"></td>
<td><input type="text" id="debit4" name="debit4" size="15" maxlength="10" onblur="calculateDebits()"></td>
<td></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
</tr>
<tr>
<td><input type="text" id="OBKey__51_8" name="OBKey__51_8" size="15" maxlength="10"></td>
<td></td>
<td><input type="text" id="credit4" name="credit4" size="15" maxlength="10" onblur="calculateCredits()"></td>
<td><input type="text" size="5" maxlength="3"></td>
<td><input type="text" size="15" maxlength="10"></td>
<td><input type="text" size="10" maxlength="8"></td>
<td><input type="text" size="60" maxlength="40"></td>
</tr>
<tr>
<td></td>
<td><input type="text" id="debitTotal" name="debitTotal"></td>
<td><input type="text" id="creditTotal" name="creditTotal"></td>
</tr>
</table>
<div class="actionButtons">
<input type="submit" class="submitButton" value="Save" name="OBBtn_Yes" onclick="return validateForm()">
<input type="reset" class="cancelButton" value="Reset" name="OBBtn_Reset">
</div>
</form>
</body>
</html>
JavaScript:
<script>
function validateForm()
{
var a = document.forms["myForm"]["debitTotal"].value;
var b = document.forms["myForm"]["creditTotal"].value;
if (a != b) {alert("NO MATCH.");
return false;
}
}
calculateDebits = function()
{
var debit1 = document.getElementById("debit1").value;
var debit2 = document.getElementById("debit2").value;
var debit3 = document.getElementById("debit3").value;
var debit4 = document.getElementById("debit4").value;
var totalDebit;
if (debit4 != "" && debit3 != "" && debit2 != "" && debit1 != "") {
totalDebit = parseFloat(debit4) + parseFloat(debit3) + parseFloat(debit2) + parseFloat(debit1);
document.getElementById("debitTotal").value = totalDebit.toFixed(2);
}
else if (debit3 != "" && debit2 != "" && debit1 != "") {
totalDebit = parseFloat(debit3) + parseFloat(debit2) + parseFloat(debit1);
document.getElementById("debitTotal").value = totalDebit.toFixed(2);
}
else if (debit2 != "" && debit1 != "") {
totalDebit = parseFloat(debit2) + parseFloat(debit1);
document.getElementById("debitTotal").value = totalDebit.toFixed(2);
}
}
calculateCredits = function()
{
var credit1 = document.getElementById("credit1").value;
var credit2 = document.getElementById("credit2").value;
var credit3 = document.getElementById("credit3").value;
var credit4 = document.getElementById("credit4").value;
var totalCredit;
if (credit4 != "" && credit3 != "" && credit2 != "" && credit1 != "") {
totalCredit = parseFloat(credit4) + parseFloat(credit3) + parseFloat(credit2) + parseFloat(credit1);
document.getElementById("creditTotal").value = totalCredit.toFixed(2);
}
else if (credit3 != "" && credit2 != "" && credit1 != "") {
totalCredit = parseFloat(credit3) + parseFloat(credit2) + parseFloat(credit1);
document.getElementById("creditTotal").value = totalCredit.toFixed(2);
}
else if (credit2 != "" && credit1 != "") {
totalCredit = parseFloat(credit2) + parseFloat(credit1);
document.getElementById("creditTotal").value = totalCredit.toFixed(2);
}
}
</script>
The result I would like to achieve is having these boxes always add and place a value in the debitTotal and creditTotal spots. These values will always be United States currency as well if that is helpful to know. I know it would likely be beneficial to have a way to check that a decimal exists from the third to last position of the debit and credit elements.
Thank you in advance for any assistance or conceptual understanding I get out of asking this question.
This sounds like you're looking for something like "sum" in excel.
First, give every element you want to sum a property that signals that.
For e.g. give your debits the class debit.
<td><input type="text" id="debit1" class="debit" name="debit1" size="15" maxlength="10"></td>
Now you can select them all using querySelectorAll:
let debits = document.querySelectorAll(".debit")
and loop through it (read about it, you will need it over and over again).
let debitValue = 0;
for (var debit in debits) {
if (debits.hasOwnProperty(debit) && debits[debit].value > 0) {
debitValue += debits[debit].value;
}
}
document.getElementById("debitTotal").value = debitValue;
Not tested but that should help you.

How to calculate values from dynamic list

If I had a list of inputs that were dynamically created, who's ID was appended to each input's name, what would be the best way of getting the value of each line item and then calculating a line by line total, as well as a grand total?
HTML:
<table>
<tr>
<td>
<input type="text" name="CompetencyList[0].Score">
<input type="text" name="SkillsList[0].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[1].Score">
<input type="text" name="SkillsList[1].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[2].Score">
<input type="text" name="SkillsList[2].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
Grand Total: <input type="text" name="grandTotal"/>
</td>
</tr>
To calculate each line
$('[name="LineTotal"]').val(function() {
return $(this).closest('td').find('input').not(this).map(function() {
return +this.value || 0;
}).get().reduce(function(a, b) { return a + b });
});
once that's done, you'd calculate the total
$('[name="grandTotal"]').val(function() {
return $('[name="LineTotal"]').map(function() {
return +this.value;
}).get().reduce(function(a, b) { return a + b });
});
$('input').on('input', calculate);
function calculate() {
$('[name="LineTotal"]').val(function() {
return $(this).closest('td').find('input').not(this).map(function() {
return +this.value || 0;
}).get().reduce(function(a, b) { return a + b });
});
$('[name="grandTotal"]').val(function() {
return $('[name="LineTotal"]').map(function() {
return +this.value;
}).get().reduce(function(a, b) { return a + b });
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" name="CompetencyList[0].Score">
<input type="text" name="SkillsList[0].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[1].Score">
<input type="text" name="SkillsList[1].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[2].Score">
<input type="text" name="SkillsList[2].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
Grand Total:
<input type="text" name="grandTotal" />
</td>
</tr>
</table>
When you create your inputs dynamically, you can add to every input a class. Then you can use jQuery to get list of items that has this class. For example:
<input type="text" class="myInput" name="CompetencyList[0].Score">
<input type="text" class="myInput" name="SkillsList[0].Score">
<input type="text" class="myInput" name="LineTotal">
And in Javascript
var myImputs = $(".myInput");
Here's a JS fiddle to how I'd do it... https://jsfiddle.net/cz6sgbyc/1/
I have added classes of lineTotal, competencyScore, and skillsScore to the associated inputs, and an id of "grandTotal" to the grand total input.
Javascript:
function updateScores() {
var grandTotal = 0;
$('.lineTotal').each( function( index, input ) {
var $parent = $(input).parent();
var thisScore = parseFloat( $('.competencyScore',$parent).val() || 0 ) + parseFloat( $('.skillsScore',$parent).val() || 0 );
grandTotal += thisScore;
$(input).val( thisScore );
});
$('#grandTotal').val( grandTotal );
}
$(function() {
$('input').change( updateScores );
});
HTML:
<table>
<tr>
<td>
<input type="text" class="competencyScore" name="CompetencyList[0].Score">
<input type="text" class="skillsScore" name="SkillsList[0].Score">
<input type="text" class="lineTotal" name="LineTotal">
</td>
<td>
<input type="text" class="competencyScore" name="CompetencyList[1].Score">
<input type="text" class="skillsScore" name="SkillsList[1].Score">
<input type="text" class="lineTotal" name="LineTotal">
</td>
<td>
<input type="text" class="competencyScore" name="CompetencyList[2].Score">
<input type="text" class="skillsScore" name="SkillsList[2].Score">
<input type="text" class="lineTotal" name="LineTotal">
</td>
<td>
Grand Total: <input type="text" id="grandTotal" name="grandTotal"/>
</td>
</tr>
</table>

How to save the content of each column of a row in a jQuery array

I am trying to create an array from the content of a table. The content of the tables looks something like this:
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
And the script that I have written is like this
$(document).on('click', '#guardarBtn', function (event) {
var content=[];
$('.rowUpdate').each(function (i) {
$(this).find('td').each(function (j, v) {
if (j != 0) {
var input = $("input", this),
name = input.attr("name").substring(0, input.attr("name").length),
value = input.val();
alert(value);
content[name] = value;
alert(JSON.stringify(content));
}
});
//alert(content);
rows.push(content);
});
});
But when I click on the button to get the content of the columns of the table and save it in an array it shows blank
UPDATED Js Fiddle link is here
Thanks in advance
Check this one. I changed var content= []; to var content= {};
$(document).on('click', '#guardarBtn', function (event) {
var content= {};
$('.rowUpdate').each(function (i) {
$(this).find('td').each(function (j, v) {
if (j != 0) {
var input = $("input", this),
name = input.attr("name").substring(0, input.attr("name").length),
value = input.val();
content[name] = value;
// alert(JSON.stringify(content));
}
});
alert(JSON.stringify(content));
// rows.push(content);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
Try this (keep the HTML the same):
$(document).on('click', '#guardarBtn', function (event) {
var rows = [];
$('.rowUpdate').each(function (i) {
var row = {};
$(this).find('td').each(function (j, v) {
if (j != 0) {
var input = $("input", this),
name = input.attr("name").substring(0, input.attr("name").length),
value = input.val();
row[name] = value;
}
rows.push(row);
});
});
Shorter way to access :
$(document).on('click', '#guardarBtn', function (event) {
var content = {};
$('.rowUpdate').each(function (i) {
$(this).find('input[type=text]').each(function(){
content[$(this).attr("name")] = $(this).val();
});
});
alert(JSON.stringify(content));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
Try This :
<form name="form_name" id='form_name'>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
</form>
js Here :
$(document).on('click', '#guardarBtn', function (event) {
var row=[];
$('.rowUpdate').each(function (i) {
var content=[];
$(this).find('input').each(function(key,value){
var field_name=$(this).attr('name');
var field_value=$(this).val();
content[field_name]=field_value;
});
row.push(content);
});
console.log(row);
});
If I well understand the question, you just need for something like this (I'm not sure however why you used nested each loops - is there any reason of this? Do you have more code in between these loops?)
$(document).on('click', '#guardarBtn', function(e){
var content={};
$('.rowUpdate td').find('input').each(function(){
content[this.name] = this.value;
});
alert(JSON.stringify(content));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>

Sum of Price is showing wrong value

I have made an invoice form.. everything is working but sum of all product price is showing wrong. I am not very good with the Javascript. Need Your help.
js for total sum:
<script type="text/javascript">
window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sum = 0;
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
</script>
html table:
Here I have declared my id's for my calculations. This
is working well.
<table>
<tr>
<td><input type="text" class="street" class="menu_name" name="user[0][name]" value=""></td>
<td><input type="text" id="q2" name="user[0][age]" value=""></td>
<td><input type="text" id="q1" class="menu_price" name="user[0][address]" value=""><br></td>
<td><input type="text" id="t3" name="user[0][email]" value=""></td>
</tr>
<tr>
<td><input type="text" class="street1" class="menu_name1" name="user[1][name]" value=""></td>
<td><input type="text" id="r2" name="user[1][age]" value=""></td>
<td><input type="text" id="r1" class="menu_price1" name="user[1][address]" value=""><br></td>
<td><input type="text" id="t4" name="user[1][email]" value=""></td>
</tr>
<tr>
<td><input type="text" class="street2" class="menu_name2" name="user[2][name]" value=""></td>
<td><input type="text" id="t2" name="user[2][age]" value=""></td>
<td><input type="text" id="t1" class="menu_price2" name="user[2][address]" value=""><br></td>
<td><input type="text" id="t7" name="user[2][email]" value=""></td>
</tr>
<tr>
<td><input type="text" class="street3" class="menu_name3" name="user[3][name]" value=""></td>
<td><input type="text" id="h2" name="user[3][age]" value=""></td>
<td><input type="text" id="h1" class="menu_price3" name="user[3][address]" value=""><br></td>
<td><input type="text" id="t8" name="user[3][email]" value=""></td>
</tr>
<tr>
<td><input type="text" class="street4" class="menu_name4" name="user[4][name]" value=""></td>
<td><input type="text" id="y2" name="user[4][age]" value=""></td>
<td><input type="text" id="y1" class="menu_price4" name="user[4][address]" value=""><br></td>
<td><input type="text" id="t9" name="user[4][email]" value=""></td>
</tr>
<tr><td>Total : <input type="text" name="total" id="total"/>
Sum //Here is my problem it's not showing correct value
</td>
</tr>
<?php echo form_submit($submit);?>
</table>
Here is a JSFiddle
I have made some changes. Actually the js is adding up all the inputs value. But you require only the value of price input.
http://fiddle.jshell.net/h9753snz/

input array values sum using javascript

I have input fields like this
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
.
.
.
<input name="total" type="text" id="total" value="">
if i enter value in unittotal field onchange the final text box value is should be sum of that unit total using javascript.
Here's the working demo for you.
You need not use duplicate id values for your HTML elements. Consider using class name instead. Refer the markup and the code that calculates the total. I hope its self-explanatory enough.
JavaScript:
function updateTotal() {
var total = 0;//
var list = document.getElementsByClassName("input");
var values = [];
for(var i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
total = values.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
document.getElementById("total").value = total;
}
HTML:
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input name="total" type="text" id="total" value="">
Like this:
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<hr>
<input type="text" size="3" id="sum" />
and the javascript:
(function () {
var elms = document.querySelectorAll('.add'),
arr = Array.prototype.slice.call(elms),
onChange = function () {
var result = 0;
arr.forEach(function (el) {
result = result + +el.value;
});
document.getElementById('sum').value = result;
};
arr.forEach(function (el) {
el.addEventListener('change', onChange);
});
}());
http://jsfiddle.net/65b6T/
try this , and see in detail in fiddle DEMO.
HTML
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
<tr>
<td width="40px">1</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr id="summation">
<td align="left">Total :</td>
<td align="left"><span id="sum">0</span>
</td>
</tr>
</table>
Javascript:
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
Here is a DEMO for this solution. http://jsfiddle.net/jxJg7/1/
NOTES:
It works only if your values are integers.
I created a function that will force the user to put numbers only on the inputs
Make sure you remove the duplicated IDs
<script type="text/javascript">
function sumofunittotal() {
var total = 0;
var cusid_ele = document.getElementsByClassName('inputtosum');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseInt(cusid_ele[i].value)) )
total += parseInt(cusid_ele[i].value);
}
document.getElementById('total').value=total;
}
function onlynumber(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
</script>
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="total" type="text" id="total" value="">

Categories