I have a code like these:
var fails = 'fail';
var sucs = 'success';
function showResult(state){
if(state){
document.getElementById("hasil").value=sucs;
}else{
document.getElementById("hasil").value=fails;
}
}
<form>
<table border='1'>
<tr>
<th>TARGET</th>
<th>RESULT</th>
<th>NOTES</th>
</tr>
<tr>
<td><input type='checkbox' name='target' onclick='showResult(this.checked);' /></td>
<td><textarea name='result[]' id='hasil'>fail</textarea></td> <td><textarea name='notes[]' class='form-control'></textarea></td>
</tr>
<tr>
<td><input type='checkbox' name='target' onclick='showResult(this.checked);' /></td>
<td><textarea name='result[]' id='hasil'>fail</textarea></td> <td><textarea name='notes[]' class='form-control'></textarea></td>
</tr>
<tr>
<td><input type='checkbox' name='target' onclick='showResult(this.checked);' /></td>
<td><textarea name='result[]' id='hasil'>fail</textarea></td> <td><textarea name='notes[]' class='form-control'></textarea></td>
</tr>
</form>
I want to create that checkbox, if it's clicked, it will change textarea on that row to success. If I uncheck, it will change back to fail. Can anyone help me?
it only works for the first row.
As #epascarello said, because ids are singular. so you need to select the parent tr, find the text area and set the value.
You can do in this way.
$('[type=checkbox]').change(function() {
if ($(this).is(":checked")) {
var $row = $(this).parents('tr');
$row.find('textarea[name="result[]"]').text("sucess");
} else {
var $row = $(this).parents('tr');
$row.find('textarea[name="result[]"]').text("fail");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table border='1'>
<tr>
<th>TARGET</th>
<th>RESULT</th>
<th>NOTES</th>
</tr>
<tr>
<td>
<input type='checkbox' name='target' />
</td>
<td>
<textarea name='result[]' id='hasil'>fail</textarea>
</td>
<td>
<textarea name='notes[]' class='form-control'></textarea>
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='target' />
</td>
<td>
<textarea name='result[]' id='hasil'>fail</textarea>
</td>
<td>
<textarea name='notes[]' class='form-control'></textarea>
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='target' />
</td>
<td>
<textarea name='result[]' id='hasil'>fail</textarea>
</td>
<td>
<textarea name='notes[]' class='form-control'></textarea>
</td>
</tr>
</form>
Related
Can someone help to select the the first row of my html table on page load using jquery or javascript.
after the page loads, it should select/highlight the first row and put all of the data from the selected row to the input boxes.
Here is my HTML CODE
HTML
<table id="tblCases">
<thead>
<tr>
<th>CASE KEY</th>
<th>DEPARTMENT CASE</th>
<th>DEPARTMENT</th>
<th style="display: none;">DEPT CODE</th>
<th style="display: none;">CHARGE</th>
<th>OFFENSE CODE</th>
<th>LAB CASE</th>
<th>INCIDENT REPORT DATE</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p>
<b>Case Details</b>
</p>
<table>
<tr>
<td>
Department Case
</td>
<td>
<input type="text" name="Department Case #" id="txtDepartmentCase" value="" />
</td>
</tr>
<tr>
<td>
Department
</td>
<td>
<select id="drpDepartment">
</select>
</td>
</tr>
<tr>
<td>
Charge
</td>
<td>
<select id="drpCharge">
</select>
</td>
</tr>
<tr>
<td>
Lab Case
</td>
<td>
<input type="text" name="Lab Case" id="txtLabCase" value="" />
</td>
</tr>
<tr>
<td>
Incident Report Date
</td>
<td>
<input type="text" name="Incident Report Date" id="txtIncidentReportDate" value="" />
</td>
</tr>
<tr>
<td>
<input type="hidden" name="Case key" id="txtCaseKey" value="" />
</td>
</tr>
</table>
<br />
<table>
<tr>
<td>
<input type="button" value="Edit" id="btnEdit" onclick="" />
</td>
<td>
<input type="button" value="Save" id="btnSave" onclick="SaveData(); this.form.reset();" />
</td>
<td>
<input type="button" value="Cancel" id="btnCancel" onclick="" />
</td>
</tr>
</table>
Here is my JS CODE, Here I include the onclick selection on the html table and also I include the function for populating the input boxes with the data from the selected row.
Javascript/jquery
$(function () {
///<summary> Highlights the row when selected</summary>
///<param name="editing" type="text">Editing state</param>
///<returns type="text"></returns>
$('#tblCases tr').click(function () {
if (isEditing) {
return;
}
$('#tblCases tr').removeClass('selectedRow');
$(this).addClass('selectedRow');
});
});
var table = document.getElementById("tblCases");
var rIndex;
for (var i = 1; i < table.rows.length; i++) {
///<summary>Display selected row data in text input.</summary>
///<param name="editing" type="text">Editing state</param>
/// <returns type="text"></returns>
table.rows[i].onclick = function () {
if (isEditing) {
return;
}
rIndex = this.rowIndex;
console.log(rIndex);
document.getElementById("txtCaseKey").value = this.cells[0].innerHTML;
document.getElementById("txtDepartmentCase").value = this.cells[1].innerHTML;
document.getElementById("drpDepartment").value = this.cells[3].innerHTML;
document.getElementById("drpCharge").value = this.cells[5].innerHTML;
document.getElementById("txtLabCase").value = this.cells[6].innerHTML;
document.getElementById("txtIncidentReportDate").value = this.cells[7].innerHTML;
};
}
function setEditingState(editing) {
///<summary>Defines the editing state which inlcude the behavior of buttons, input fields and row selection if a certain button was clicked</summary>
///<param name="editing" type="button; text">Editing state</param>
isEditing = editing;
// Disable or enable fields.
$('#txtDepartmentCase').attr('disabled', !editing);
$('#drpDepartment').attr('disabled', !editing);
$('#drpCharge').attr('disabled', !editing);
$('#txtLabCase').attr('disabled', !editing);
$('#txtIncidentReportDate').attr('disabled', !editing);
// Disable or enable buttons.
$('#btnEdit').attr('disabled', editing);
$('#btnSave').attr('disabled', !editing);
$('#btnCancel').attr('disabled', !editing);
}
Here's something to get you started:
var first_name = $('#source_table').find('tbody tr:first td:first').text();
var last_name = $('#source_table').find('tbody tr:first td:nth-child(2)').text();
var age = $('#source_table').find('tbody tr:first td:nth-child(3)').text();
$('#first_name').val(first_name);
$('#last_name').val(last_name);
$('#age').val(age);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="source_table" border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joe</td>
<td>Hunt</td>
<td>20</td>
</tr>
<tr>
<td>Jane</td>
<td>Middletow</td>
<td>19</td>
</tr>
</tbody>
</table>
<br/>
<table>
<tr>
<td>First Name :</td>
<td><input type="text" id="first_name"></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input type="text" id="last_name"></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="text" id="age"></td>
</tr>
I'm trying to subtract two totals.
I have one table for incomes, were the final row is the "total incomes" and another table for expenses, with a final row for the "total expenses"
I need to add another function that calculates the total income minus the total expenses. I also need to show a negative amount in case the expenses are greater than the incomes.
My problem is, I don't quite understand how to use the value that its stored on my previous function so I can reuse it on the new one. I'm fairly new to javascript/jquery so I'm having troubles understanding the documentation.
Any guidance on this will be very much appreciated
Here is the js
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txtA").each(function () {
$(this).keyup(function () {
calculateSumA();
calculateSubstraction();
});
});
});
function calculateSumA() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txtA").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
$("#sumA").html(sum.toFixed(2));
}
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
calculateSubstraction();
});
});
});
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));
}
function calculateSubstraction() {
var subs = calculateSum() - calculateSumA();
$("#subs").html(subs.toFixed(2));
}
here is the html
<body>
<table width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td> </td>
<td align="right">total income:</td>
<td align="center"><span id="sumA">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td> </td>
<td align="right">total expenses:</td>
<td align="center"><span id="sum">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="su">0</span>
</td>
</tr>
</table>
http://jsfiddle.net/gnzLwzuy/5/
I know it could be optimized, as I'm repeating the code too much, but If I change it too much It stops working.
(I have too much to learn...)
Just to complement Guruprasad answer, and to responde directly to how can a function access a value calculated by another function.
The easy way:
1 - declare global variables and use them inside your functions.
var foo;
function calculateSumA() {
....
foo = some value;
}
function OtherFunc() {
....
var localVar = foo;
}
2 - make the functions return a value and store it somewhere other functions can access (e.g a global variable);
Not so simple way:
You can use closures to create the illusion of private members.
I wrote an article on JS Closures. I believe it will help you understand the concept quite well, if you are curious about it: https://usonsci.wordpress.com/2014/10/04/closure-with-javascript/
However you are calling calculateSubstraction on keyup of each textbox just take the value from total of each section and subtract it accordingly as below:
function calculateSubstraction() {
var subs=parseFloat($("#sumA").text()) - parseFloat($("#sum").text())
$("#su").html(subs);
}
DEMO
Update
Here is the more optimized version of your code. I prefer blur event than keyup since its more reliable to calculate and reduces the firing of event on every keypress
$(document).ready(function () {
var income = 0;//variable to hold income
var expense= 0; //variable to hold expense
$(".txtA,.txt").blur(function () { //attach event to multiple elements
$(this).each(function () {//loop through each of them
if (!isNaN(this.value) && this.value.length != 0) {
if($(this).hasClass('txt')) //if it is expense
expense += parseFloat(this.value); //add it to expense
else
income+=parseFloat(this.value); //add it to income
}
});
if($(this).hasClass('txt'))
$("#sum").html(expense.toFixed(2)); //display based on income or expense
else
$("#sumA").html(income.toFixed(2));
calculateSubstraction();//this remains same
});
});
Updated DEMO
DEMO
You need to return a value from the add functions so add
return sum.toFixed(2);
return sum.toFixed(2);
from the two function and did the subtraction from the subtract function
var data = calculateSum();
var dataa = calculateSumA();
var subs = dataa-data;
$("#su").html(subs.toFixed(2));
Just Replace your calculateSubstraction() function with this :
function calculateSubstraction() {
var Income = parseFloat($('#sumA').html());
var Expense = parseFloat($('#sum').html());
var subs = Income - Expense;
$("#su").html(subs.toFixed(2));
}
Using jQuery, you can have a simple calculation like
jQuery(function() {
var sum = {
income: 0,
deduction: 0
};
$('input.entry').keyup(function() {
var $table = $(this).closest('table'),
total = 0;
$table.find('input.entry').each(function() {
total += +this.value || 0;
});
$table.find('span.total').html(total)
sum[$table.data('type')] = total;
$('#su').html(sum.income - sum.deduction);
})
})
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border-color: white;
background-color: powderblue;
}
input.entry {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1" class="entry" data-type="income">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td> </td>
<td align="right">total income:</td>
<td align="center"><span class="total">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1" class="entry" data-type="deduction">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td> </td>
<td align="right">total expenses:</td>
<td align="center"><span class="total">0</span></td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="su">0</span>
</td>
</tr>
</table>
I've made a pure Javascript version of your code, and added two new functionalities:
A button to dynamically add new rows to the income and expense tables.
And remove the ability of user adding anything other than numbers to the textfields.
The full commented code is below:
/* when all elements of the page are available */
document.addEventListener('DOMContentLoaded', function() {
/* get the tables income and expense, and the 'total' fields */
var income = document.getElementById('income'),
expense = document.getElementById('expense'),
totalIncome = document.getElementById('totalIncome'),
totalExpense = document.getElementById('totalExpense'),
total = document.getElementById('total');
/* create the calculate function */
function calculate(e) {
/* get all the textfields of each table */
var incomes = [].slice.call(income.querySelectorAll('input')),
expenses = [].slice.call(expense.querySelectorAll('input'));
/* calculate the sum of the fields by using
- map to convert the values to numbers
- and reduce to sum those values */
var sumIncome = incomes.map(function(el) {
/* don't allow users to input other values than numbers */
el.value = el.value.replace(/[^0-9\.]/g, '');
return Number(el.value);
}).reduce(function(a, b) {
return a + b;
});
var sumExpense = expenses.map(function(el) {
/* don't allow users to input other values than numbers */
el.value = el.value.replace(/[^0-9\.]/g, '');
return Number(el.value);
}).reduce(function(a, b) {
return a + b;
});
/* change the totalIncome and totalExpense labels */
totalIncome.textContent = sumIncome;
totalExpense.textContent = sumExpense;
/* change the total remaining label */
total.textContent = sumIncome - sumExpense;
}
/* add the event handlers to the oninput event to both tables
they will call the calculate function above when they happen */
income.addEventListener('input', calculate);
expense.addEventListener('input', calculate);
/* this is a bonus, I've added 'new' buttons to dynamically add more rows */
document.addEventListener('click', function(e) {
var el = e.target;
if (el.className === 'new') {
var table = el.parentNode.parentNode.parentNode,
tr = document.createElement('tr');
tr.innerHTML = '<td>' + [].slice.call(table.querySelectorAll('tr')).length + '</td>\
<td>income</td>\
<td>\
<input class="txtA" type="text" />\
</td>';
table.insertBefore(tr, el.parentNode.parentNode);
}
});
});
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border-color: white;
background-color: powderblue;
}
.txt,
.txtA {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<table id='income' width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td>
<button class="new">new</button>
</td>
<td align="right">total income:</td>
<td align="center"><span id="totalIncome">0</span>
</td>
</tr>
</table>
<br/>
<table id='expense' width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>
<button class="new">new</button>
</td>
<td align="right">total expenses:</td>
<td align="center"><span id="totalExpense">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="total">0</span>
</td>
</tr>
</table>
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("input[name='data[Store][id][]']").change(function () {
if ($("input[name='data[Store][id][]']").is(':checked')) {
var input_value = parseFloat($(this).val());
var brand= $(this).closest('tr').find('#brand').text();
var number1 = $(this).closest('tr').find('input[name="data[store][stock_received][]"]').attr('disabled', 'disabled');
}else{
var number1 = $(this).closest('tr').find('input[name="data[store][stock_received][]"]').prop("disabled", false);
}
});
});
</script>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td><input id='tmpid' name="data[store][stock_received][]" ></td>
<td><input type='checkbox' name='data[Store][id][]'></td>
</tr>
<tr>
<td><input id='tmpid' name="data[store][stock_received][]"></td>
<td><input type='checkbox' name='data[Store][id][]'></td>
</tr>
<tr>
<td><input id='tmpid' name="data[store][stock_received][]"></td>
<td><input type='checkbox' name='data[Store][id][]'></td>
</tr>
<tr>
<td><input id='tmpid' name="data[store][stock_received][]"></td>
<td><input type='checkbox' name='data[Store][id][]'></td>
</tr>
<tr>
<td><input id='tmpid' name="data[store][stock_received][]"></td>
<td><input type='checkbox' name='data[Store][id][]'></td>
</tr>
</table>
</body>
</html>
jquery disable is not working properly and I want to disable id=tmpid near near name='data[Store][id][]'.
Currently i m using name='data[store][stock_received][]' name near name='data[Store][id][]'.
For individual check box its working fine . If I select all then i uncheck then its not working properly
1)ID should be unique
2)You are using parseFloat() on an string
3)$("input[name='data[Store][id][]']").is(':checked') seems in correct
should be $(this).is(":checked")
$(document).ready(function() {
$("input[name='data[Store][id][]']").change(function() {
if ($(this).is(':checked')) {
var input_value = $(this).val();
var brand = $(this).closest('tr').find('#brand').text();
var number1 = $(this).closest('tr').find('input[name="data[store][stock_received][]"]').attr('disabled', 'disabled');
} else {
var number1 = $(this).closest('tr').find('input[name="data[store][stock_received][]"]').prop("disabled", false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>
<input class='tmpid' name="data[store][stock_received][]">
</td>
<td>
<input type='checkbox' name='data[Store][id][]'>
</td>
</tr>
<tr>
<td>
<input class='tmpid' name="data[store][stock_received][]">
</td>
<td>
<input type='checkbox' name='data[Store][id][]'>
</td>
</tr>
<tr>
<td>
<input class='tmpid' name="data[store][stock_received][]">
</td>
<td>
<input type='checkbox' name='data[Store][id][]'>
</td>
</tr>
<tr>
<td>
<input class='tmpid' name="data[store][stock_received][]">
</td>
<td>
<input type='checkbox' name='data[Store][id][]'>
</td>
</tr>
<tr>
<td>
<input class='tmpid' name="data[store][stock_received][]">
</td>
<td>
<input type='checkbox' name='data[Store][id][]'>
</td>
</tr>
</table>
I can't find what is wrong in my code, as it does nothing...
my js has:
function calc()
{
for(i=1;i<=4;i++)
{
document.getElementById("cost"+i).value= (document.getElementById("pret"+i).value*document.getElementById("cant"+i).value)*1.24;
document.biblioteca.total.value+=document.getElementById("cost"+i).value;
}
}
and the html is:
<form name="biblioteca">
<table width=600 border="3">
<tr>
<th width="50%">Carte</th>
<th width="15%">Pret</th>
<th width="15%">Cantitate</th>
<th>Cost(TVA inclus)</th>
</tr>
<tr>
<td>Manuscrisul gasit la Accra - Paulo Coelho</td>
<td id="pret1" value="20">20</td>
<td><input type="text" value="" id="cant1"></td>
<td><textarea name="cost1" id="cost1" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Poarta coliviei - Katie Hickman</td>
<td id="pret2" value="10">10</td>
<td><input type="text" value="" id="cant2"></td>
<td><textarea name="cost2" id="cost2" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Cincizeci de umbre ale lui Grey - E.L. James </td>
<td id="pret3" value="44">44</td>
<td><input type="text" value="" id="cant3"></td>
<td><textarea name="cost3" id="cost3" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Ciresarii. Vol.2: Castelul Fetei In Alb - Constantin Chirita</td>
<td id="pret4" value=6>6</td>
<td><input type="text" value="" id="cant4"></td>
<td><textarea name="cost4" id="cost4" rows="1" value=""></textarea></td>
</tr>
<tr>
<td colspan=2></td>
<td>Total:</td>
<td><textarea name="total" rows="1" readonly value=""></textarea></td>
</tr>
</table>
<input type="button" name="calc" value="Caluleaza" onclick="calc()">
</form>
It should take the value from the second column, multiply it by the third column, and then by 1.24, and write the result in the forth column. then, this result should be summarized in the last column, of the last row, the total. but it does nothing. i tried different ways, stopped at this one because was the first that came in mind. I also tried assigning object=document.getElementById("cost"+i) then use object.value, but it's the same thing, and it does not work. I can'n find what's wrong.
After comments, whole html looks like this:
<html>
<head>
<script type="text/javascript">
function calculate()
{
document.biblioteca.total.value = 0;
for(i=1;i<=4;i++)
{
document.getElementById("cost"+i).value= (parseInt(document.getElementById("pret"+i).innerText)*parseFloat(document.getElementById("cant"+i).value))*1.24;
document.biblioteca.total.value = parseFloat(document.biblioteca.total.value) + parseFloat(document.getElementById("cost"+i).value);
}
}
</script>
</head>
<body>
<h1>Biblioteca</h1>
<form name="biblioteca">
<table width=600 border="3">
<tr>
<th width="50%">Carte</th>
<th width="15%">Pret</th>
<th width="15%">Cantitate</th>
<th>Cost(TVA inclus)</th>
</tr>
<tr>
<td>Manuscrisul gasit la Accra - Paulo Coelho</td>
<td id="pret1">20</td>
<td><input type="text" value="" id="cant1"></td>
<td><textarea name="cost1" id="cost1" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Poarta coliviei - Katie Hickman</td>
<td id="pret2">10</td>
<td><input type="text" value="" id="cant2"></td>
<td><textarea name="cost2" id="cost2" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Cincizeci de umbre ale lui Grey - E.L. James </td>
<td id="pret3">44</td>
<td><input type="text" value="" id="cant3"></td>
<td><textarea name="cost3" id="cost3" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Ciresarii. Vol.2: Castelul Fetei In Alb - Constantin Chirita</td>
<td id="pret4">6</td>
<td><input type="text" value="" id="cant4"></td>
<td><textarea name="cost4" id="cost4" rows="1" value=""></textarea></td>
</tr>
<tr>
<td colspan=2></td>
<td>Total:</td>
<td><textarea name="total" rows="1" readonly value=""></textarea></td>
</tr>
</table>
<input type="button" value="Caluleaza" onclick="calculate()">
</form>
</body>
</html>
either I;m very tired and can't see some obvious stupid mistake, or there is something fishy....because still doesn't work.
The values stored by those <input> elements aren't numbers. They're strings. You need to convert them into floats or integers:
var total_element = document.biblioteca.total;
var cost_element = document.getElementById("cost" + i);
var pret_element = document.getElementById("pret" + i);
var cant_element = document.getElementById("cant" + i);
var pret = parseFloat(pret_element.value);
var cant = parseFloat(cant_element.value);
cost_element.value = pret * cant * 1.24;
total_element.value += cost_element.value;
To start, you are trying to do math on string values when you are grabbing the value from the input tags.
Also, your function is not running because you can not use calc() as the function name ( for some reason)
Try replacing your code with this.
JS:
function calculate()
{
document.biblioteca.total.value = 0;
for(i=1;i<=4;i++)
{
document.getElementById("cost"+i).value= (parseInt(document.getElementById("pret"+i).innerText)*parseFloat(document.getElementById("cant"+i).value))*1.24;
document.biblioteca.total.value = parseFloat(document.biblioteca.total.value) + parseFloat(document.getElementById("cost"+i).value);
}
}
HTML:
<form name="biblioteca">
<table width=600 border="3">
<tr>
<th width="50%">Carte</th>
<th width="15%">Pret</th>
<th width="15%">Cantitate</th>
<th>Cost(TVA inclus)</th>
</tr>
<tr>
<td>Manuscrisul gasit la Accra - Paulo Coelho</td>
<td id="pret1" value="20">20</td>
<td><input type="text" value="" id="cant1"></td>
<td><textarea name="cost1" id="cost1" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Poarta coliviei - Katie Hickman</td>
<td id="pret2" value="10">10</td>
<td><input type="text" value="" id="cant2"></td>
<td><textarea name="cost2" id="cost2" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Cincizeci de umbre ale lui Grey - E.L. James </td>
<td id="pret3" value="44">44</td>
<td><input type="text" value="" id="cant3"></td>
<td><textarea name="cost3" id="cost3" rows="1" value=""></textarea></td>
</tr>
<tr>
<td>Ciresarii. Vol.2: Castelul Fetei In Alb - Constantin Chirita</td>
<td id="pret4" value=6>6</td>
<td><input type="text" value="" id="cant4"></td>
<td><textarea name="cost4" id="cost4" rows="1" value=""></textarea></td>
</tr>
<tr>
<td colspan=2></td>
<td>Total:</td>
<td><textarea name="total" rows="1" readonly value=""></textarea></td>
</tr>
</table>
<input type="button" name="calc" value="Caluleaza" onclick="calculcate()">
</form>
i have a form with Jquery .validation().
Form:
<form....>
<table cellspacing="0" cellpadding="0">
<tr>
<td>Name: </td>
<td><input type='text' name='Name'/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type='text' name='LastName'/></td>
</tr>
<tr>
<td>Address: </td>
<td><input type='text' name='Address'/></td>
</tr>
</table>
<input type='submit' name='enter' value='submit'/>
</form>
I would like to print errors like this:
Is it possible?
Thanks in advance :)
Demo Here
HTML
<form name="test">
<table cellspacing="1" cellpadding="1">
<tr>
<td>Name: </td>
<td><input type='text' name='Name'/>
<span class="error_span">Enter name</span>
</td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type='text' name='LastName'/>
<span class="error_span">Enter last name</span>
</td>
</tr>
<tr>
<td>Address: </td>
<td><input type='text' name='Address'/>
<span class="error_span">Enter address</span>
</td>
</tr>
</table>
<input type='button' id='submit' name='enter' value='submit'/>
</form>
jQuery
$(document).ready(function(){
$("#submit").click(function(){
$('input').each(function(index) {
if($(this).val()=="") {
$(this).addClass("has_error");
$(this).siblings(".error_span").show();
}else{
$(this).removeClass("has_error");
$(this).siblings(".error_span").hide();
}
});
});
});
CSS
.error_span{
color:red;
display:none;
}
.has_error{
border:1px solid red;
}
Demo Here
You can use onsubmit attribute of your form to execute the javascript and stop the form from submitting if there is validation error
You can do in Two ways..
1)
<form....>
<table cellspacing="0" cellpadding="0">
<tr>
<td>Name: </td>
<td><input type='text' name='Name'/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type='text' name='LastName'/></td>
</tr>
<tr>
<td></td>
<td>Name Is Required</td>
</tr>
<tr>
<td>Address: </td>
<td><input type='text' name='Address'/></td>
</tr>
</table>
<input type='submit' name='enter' value='submit'/>
</form>
or
2)
<form....>
<table cellspacing="0" cellpadding="0">
<tr>
<td>Name: </td>
<td><input type='text' name='Name'/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type='text' name='LastName'/> <br />Name Is Required</td>
</tr>
<tr>
<td>Address: </td>
<td><input type='text' name='Address'/></td>
</tr>
</table>
<input type='submit' name='enter' value='submit'/>
</form>
You have to use custom validation code for doing like that. Check this link. http://docs.jquery.com/Plugins/Validation/Validator/addMethod