This was my code. When I click the add row it will add the row below. but the on click event is working in the first row alone.
It was not working in the rest of the rows.
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="http://web-86d95219-b398-4432-85a8-fae716ac3a54.runnablecodesnippets.com/css/datepicker.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://web-86d95219-b398-4432-85a8-fae716ac3a54.runnablecodesnippets.com/js/bootstrap-datepicker.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Name
</th>
<th class="text-center">
Mail
</th>
<th class="text-center">
Mobile
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input id = "date0" type="text" name='name0' placeholder='Name' class="form-control"/>
</td>
<td>
<input type="text" name='mail0' placeholder='Mail' class="form-control"/>
</td>
<td>
<select name="category" class="input category"><option selected>Choose </option><option >Chooser2</option></select>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
<script>
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
var datepic = "#date" + i;
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input id = 'date"+i+"' name='name"+i+"' type='text' placeholder='Name' class='form-control input-md' /> </td><td><input name='mail"+i+"' type='text' placeholder='Mail' class='form-control input-md'></td><td><select class='input category'><option selected>d</option></select></td>");
$(datepic).datepicker();
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
$(".category").click(function(){
alert('df');
});
});
$(function() {
var startDate = new Date(2015,2,30);
$('#date0').datepicker('setDate',startDate);
});
</script>
</body>
</html>
You can check in the snippet.
Thanks in advance.
For dynamically added row, add click event handle using .on() because by the time you attach a click handler for the add row button dynamica rows were not there and hence you need attach click event handler using document which will delegate the event to matched selector.
$(document).ready(function(){
var i=1;
$(document).on("click", "#add_row", function(){
var datepic = "#date" + i;
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input id = 'date"+
i+"' name='name" + i +
"' type='text' placeholder='Name' class='form-control input-md'/>"
+ "</td><td><input name='mail" +
i + "' type='text' placeholder='Mail' class='form-control input-md'>"
+"</td><td><select class='input category'><option selected>d</option></select>"
+"</td>");
$(datepic).datepicker();
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$(document).on("click","#delete_row", function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
$(document).on("click", ".category", function(){
alert('df');
});
});
Change this:
$(".category").click(function(){
alert('df');
});
to this:
$(document).on('click', '.category', function(){
alert('df');
});
Its is called delegated events.
Snippet:
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="http://web-86d95219-b398-4432-85a8-fae716ac3a54.runnablecodesnippets.com/css/datepicker.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://web-86d95219-b398-4432-85a8-fae716ac3a54.runnablecodesnippets.com/js/bootstrap-datepicker.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Name
</th>
<th class="text-center">
Mail
</th>
<th class="text-center">
Mobile
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input id = "date0" type="text" name='name0' placeholder='Name' class="form-control"/>
</td>
<td>
<input type="text" name='mail0' placeholder='Mail' class="form-control"/>
</td>
<td>
<select name="category" class="input category"><option selected>Choose </option><option >Chooser2</option></select>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
<script>
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
var datepic = "#date" + i;
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input id = 'date"+i+"' name='name"+i+"' type='text' placeholder='Name' class='form-control input-md' /> </td><td><input name='mail"+i+"' type='text' placeholder='Mail' class='form-control input-md'></td><td><select class='input category'><option selected>d</option></select></td>");
$(datepic).datepicker();
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
$(document).on('click', '.category', function(){
alert('df');
});
});
$(function() {
var startDate = new Date(2015,2,30);
$('#date0').datepicker('setDate',startDate);
});
</script>
</body>
</html>
Related
I have been facing a problem that I have been looking everywhere for a soultion.
I want to make a page where you can insert new rows to a form table, then use these values to insert into database.
Here is an image of how the page I want to make will look like. sales form
The idea behind the page is that one receipt id will be generated and inside there can be many items that users can add, hence the multiple rows.
Here is the code for the form page.
<?php
include('session.php');
?>
<?php
$ItemID = "ItemID";
$ItemName = "ItemName";
$UnitPrice = "UnitPrice";
$sql = "SELECT ItemID,ItemName,UnitPrice FROM Item";
$result = $db->query($sql);
?>
<html>
<head>
<title>Add Sales</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="text-center">
<h1>Add new Sales Record</h1>
</div>
<div class="container">
<button class="w3-button w3-black w3-round-large">Back</button>
</div>
<div class="container" align="right">
<table class="table-sm">
<tbody>
<tr class="table-primar">
<th scope="col" style="padding-right: 50px;">ItemID</th>
<th scope="col" style="padding-right: 50px">ItemName</th>
<th scope="col">UnitPrice</th>
</tr>
<?php
while($rows = $result->fetch_assoc()) {
?>
<tr class="contents">
<td><?php echo $rows[$ItemID]; ?></td>
<td><?php echo $rows[$ItemName]; ?></td>
<td><?php echo $rows[$UnitPrice]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<hr>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
ItemID
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
Price Sold
</th>
<th class="text-center">
Branch ID
</th>
<th class="text-center">
EmployeeID
</th>
<th class="text-center">
MemberID
</th>
</tr>
</thead>
<tbody>
<form action="addsales.php" method="post">
<tr id='addr0'>
<td>
<input type="text" name='item[][itemid]' placeholder='ItemID' class="form-control"/>
</td>
<td>
<input type="text" name='item[][amount]' placeholder='Amount' class="form-control"/>
</td>
<td>
<input type="text" name='item[][pricesold]' placeholder='PriceSold' class="form-control"/>
</td>
<td>
<input type="text" name='item[][branchid]' placeholder='BranchID' class="form-control"/>
</td>
<td>
<input type="text" name='item[][employeeid]' placeholder='EmployeeID' class="form-control"/>
</td>
<td>
<input type="text" name='item[][memberid]' placeholder='MemberID' class="form-control"/>
</td>
</tr>
<tr id='addr1'></tr>
<input class="w3-button w3-black w3-round-large" type="submit" name='submit' value="Submit"/>
</form>
</tbody>
</table>
</div>
</div>
<button id="add_row" class="w3-button w3-black w3-round-large" style="position: absolute; right: 130px;">New row</button>
</div>
<script type="text/javascript">
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr'+(i-1)).find('input').attr('disabled',true);
$('#addr' + i).html("<td><input name='item[][itemid]' placeholder='ItemID' class='form-control input-md'/></td><td><input type='text' name='item[][amount]' placeholder='Amount' class='form-control input-md'/></td><td><input type='text' name='item[][pricesold]' placeholder='PriceSold' class='form-control input-md'/></td><td><input type='text' name='item[][branchid]' placeholder='BranchID' class='form-control input-md'/></td><td><input type='text' name='item[][employeeid]' placeholder='EmployeeID' class='form-control input-md'/></td><td><input type='text' name='item[][memberid]' placeholder='MemberID' class='form-control input-md'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
</script>
</body>
</html>
The values will be handled in another php page.
<?php
include('session.php');
print_r($_POST);
$ItemIDs = $_POST['itemid'];
$PriceSolds = $_POST['pricesold'];
$QtySolds = $_POST['amount'];
$Date = date("Y-m-d h:i:sa");
$BranchIDs = $_POST['branchid'];
$EmployeeIDs = $_POST['employeeid'];
$MemberIDs = $_POST['memberid'];
$size = sizeof($ItemIDs);
$sql2 = "INSERT INTO Receipt_seq VALUES (NULL);";
$db->query($sql2);
for($i = 0; $i < $size; $i++ ){
$ItemID = $ItemIDs[$i];
$PriceSold = $PriceSolds[$i];
$QtySold = $QtySolds[$i];
$BranchID = $BranchIDs[$i];
$EmployeeID = $EmployeeIDs[$i];
$MemberID = $MemberIDs[$i];
$sql = "INSERT INTO Receipt (ItemId,PriceSold,QtySold,RDate,BranchID,EmployeeID,MemberID) VALUES ('{$ItemID}', '{$PriceSold}', '{$QtySold}','{$Date}','$BranchID','$EmployeeID','$MemberID')";
$db->query($sql);
}
?>
The Id for the receipt will be automatically generated using a trigger system. The only problem I have right now is that I can send in one row data just fine. But the moment I add a second row, it gives me an error Undefine index .... I tried to use print_r($_POST); to see what is happening and this is the result. When I submitted one row of data it looked fine one row But when I added the second row it gave me this error more than one row error. I am a beginner at making website so I am not sure what I am doing is correct or not. Please help, thank you. I added and image of what my sales page will look like so you might have a better understanding of what I am trying to do Sales page.
Just to clarify points above, you MUST set the inputs with attribute readonly NOT disabled so that the previous input rows get included.
Then just follow what I said in the comments by adding (concatenating) the index into the dynamically added input rows:
$('#addr' + i).html("<td><input name='item["+i+"][itemid]'
// ^ add the dynamic index here
Sidenote: Don't forget to wrap the table with the form tag
I'll just add the important bits, so all in all:
a. Form tag before table tag
<div class="col-md-12 column">
<form action="" method="post"> <!-- this -->
<table class="table table-bordered table-hover" id="tab_logic">
b. change to readonly instead of disabled attribute and add the index in the "add row"
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr'+(i-1)).find('input').attr('readonly',true);
$('#addr' + i).html("<td><input name='item["+i+"][itemid]' placeholder='ItemID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][amount]' placeholder='Amount' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][pricesold]' placeholder='PriceSold' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][branchid]' placeholder='BranchID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][employeeid]' placeholder='EmployeeID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][memberid]' placeholder='MemberID' class='form-control input-md'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
Full code:
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr'+(i-1)).find('input').attr('readonly',true);
$('#addr' + i).html("<td><input name='item["+i+"][itemid]' placeholder='ItemID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][amount]' placeholder='Amount' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][pricesold]' placeholder='PriceSold' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][branchid]' placeholder='BranchID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][employeeid]' placeholder='EmployeeID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][memberid]' placeholder='MemberID' class='form-control input-md'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form action="" method="post">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
ItemID
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
Price Sold
</th>
<th class="text-center">
Branch ID
</th>
<th class="text-center">
EmployeeID
</th>
<th class="text-center">
MemberID
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
<input type="text" name='item[0][itemid]' placeholder='ItemID' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][amount]' placeholder='Amount' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][pricesold]' placeholder='PriceSold' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][branchid]' placeholder='BranchID' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][employeeid]' placeholder='EmployeeID' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][memberid]' placeholder='MemberID' class="form-control"/>
</td>
</tr>
<tr id='addr1'></tr>
<input class="w3-button w3-black w3-round-large" type="submit" name='submit' value="Submit"/>
</tbody>
</table>
</form>
</div>
</div>
<button id="add_row" class="w3-button w3-black w3-round-large" style="position: absolute; right: 130px;">New row</button>
</div>
This was working fine before without the <select> and <option> drop-downs...
but trying to add a drop-down menu to this, it is functioning improperly (see the fiddle or more details below). Not seeing any errors popping up in console.
JSFiddle (Working): https://jsfiddle.net/zxqrpLvo/
JSFiddle (Not Working*): https://jsfiddle.net/a2a4584z/1/
Working (without Select Drop-Down):
HTML
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6" id="inputform">
<form id="inventorytoadd">
<table class="table table-striped table-responsive table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center" width="10%">
#
</th>
<th class="text-center" width="68%">
SKU
</th>
<th class="text-center" width="22%">
Quantity
</th>
</tr>
</thead>
<tbody>
<tr id='addi0'>
<td class="text-center numcell" width="10%">
1
</td>
<td width="68%">
<input type="text" name='sku[]' id="sku0" placeholder='SKU' class="form-control"/>
</td>
<td width="22%">
<input type="text" name='qty[]' id="qty0" placeholder='Quantity' class="form-control"/>
</td>
</tr>
<tr id='addi1'></tr>
</tbody>
</table>
</form>
</div>
<div class="col-md-3">
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 add-delete-rows" id="inventory-add">
<button id="add_row" class="btn btn-primary pull-left">Add Row</button><button id='delete_row' class="pull-right btn btn-danger">Delete Row</button>
</div>
<div class="col-md-3">
</div>
</div>
Along with accompanying jquery code
jQuery/Javascript
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addi' + i).html("<td class='text-center numcell'>" + (i + 1) + "</td><td><input name='sku[]' type='text' placeholder='SKU' class='form-control input-md' /> </td><td><input name='qty[]' type='text' placeholder='Quantity' class='form-control input-md'></td>");
$('#tab_logic').append('<tr id="addi' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addi" + (i - 1)).html('');
i--;
}
});
});
Not Working with Select Drop-Down
HTML
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10" id="inputform">
<form id="inventorytoadd">
<table class="table table-striped table-responsive table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
SKU
</th>
<th class="text-center">
Category
</th>
<th class="text-center">
Quantity
</th>
</tr>
</thead>
<tbody>
<tr id='addi0'>
<td class="text-center numcell">
1
</td>
<td>
<input type="text" name='sku[]' id="sku0" placeholder='SKU' class="form-control"/>
</td>
<td>
<div class="select">
<select name="category[]">
<option title="Gaskets" value="Gaskets">Gaskets</option>
<option title="Oil Filters" value="Oil Filters">Oil Filters</option>
<option title="Air Filters" value="Air Filters">Air Filters</option>
</select>
</div>
</td>
<td>
<input type="text" name='qty[]' id="qty0" placeholder='Quantity' class="form-control"/>
</td>
</tr>
<tr id='addi1'></tr>
</tbody>
</table>
</form>
</div>
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 add-delete-rows" id="inventory-add">
<button id="add_row" class="btn btn-primary">Add Row</button><button id='delete_row' class="btn btn-danger">Delete Row</button>
</div>
<div class="col-md-3">
</div>
</div>
jQuery/Javascript
$(document).ready(function() {
var i = 1;
$('#add_row').click(function() {
$('#addi' + i).html('<td class="text-center numcell">' + (i + 1) + '</td><td><input name="sku[]" type="text" placeholder="SKU" class="form-control input-md" /></td><td><div class="select"><select name="category[]"><option title="Gaskets" value="Gaskets">Gaskets</option><option title="Oil Filters" value="Oil Filters">Oil Filters</option><option title="Air Filters" value="Air Filters">Air Filters</option></select></div></td><td><input name="qty[]" type="text" placeholder="Quantity" class="form-control input-md"></td>');
$('tab_logic').append('<tr id="addi' + (i + 1) + '"></tr>');
i++;
});
$('#delete_row').click(function() {
if (i > 1) {
$('#addi' + (i - 1)).html("");
i--;
}
});
});
As you can see by the fiddle, it is only allowing me to add a row once.. and for some reason it takes two clicks to delete a row. It appears to be identical code functionality from what I can see, what is the issue here?
you miss "#" on your selector: $('#tab_logic')
$(document).ready(function() {
var i = 1;
$('#add_row').click(function() {
$('#addi' + i).html('<td class="text-center numcell">' + (i + 1) + '</td><td><input name="sku[]" type="text" placeholder="SKU" class="form-control input-md" /></td><td><div class="select"><select name="category[]"><option title="Gaskets" value="Gaskets">Gaskets</option><option title="Oil Filters" value="Oil Filters">Oil Filters</option><option title="Air Filters" value="Air Filters">Air Filters</option></select></div></td><td><input name="qty[]" type="text" placeholder="Quantity" class="form-control input-md"></td>');
$('#tab_logic').append('<tr id="addi' + (i + 1) + '"></tr>');
i++;
});
$('#delete_row').click(function() {
if (i > 1) {
$('#addi' + (i - 1)).html("");
i--;
}
});
});
I have a table,it can add dynamical rows.what i'm trying to do is,calculate amount column sum and display in Expences field.then reduce expencess from income and display total in balance field
eg:
when user fill first row with book and price for book in amount column.then click add item button and add another row.that time calculate sum of book and pen and display in expences field.total will display balance field.
<div class="col-xs-12">Income (Rs) : <input type="number" min="0.01" step="0.01" name="income" value="2536.67" id="income" >
</div>
<div class="col-xs-12">Expences (Rs) : <input type="number" min="0.01" step="0.01" name="expence" value="" readonly id="expence">
</div>
<div class="col-xs-12">Balance (Rs) : <input type="number" min="0.01" step="0.01" name="balance" value="" readonly id="balance">
</div>
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Category
</th>
<th class="text-center">
Item Name
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<select class="form-control" name="cat">
<option value="bill">Bill</option>
<option value="exchange">Exchange</option>
</select>
</td>
<td>
<input type="text" name='name0' placeholder='Item Name' class="form-control"/>
</td>
<td class='amount'>
<input type="number" name='amount' placeholder='Amount' class="form-control" id='amount'/>
</td>
<td>
<input type="file" class="form-control" name="upload" />
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<a id="add_row" class="btn btn-default pull-left">Add Item</a><a id='delete_row' class="pull-right btn btn-default">Delete Item</a>
<button type="Submit" class="btn btn-success pull-right btn-lg" >Submit</button>
Add,delete row query
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><select class='form-control' name='cat"+i+"'><option value='bill'>Bill</option><option value='exchange'>Exchange</option></select><td><input name='name"+i+"' type='text' placeholder='Item Name' class='form-control input-md' /> </td><td class='amount'><input name='mail"+i+"' type='number' min='0.01' step='0.01' placeholder='Amount' id='amount"+i+"' class='form-control input-md'></td><td><input type='file' name='upload"+i+"' class='form-control'/></td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
</script>
i tried this query.this is cal from table td class.
$(document).ready(function(){
$('.amount').each(function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
$(".amount").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$('#expence').text(sum);
};
This might be because, your function calculateSum(); isn't triggering. You can probably use .change to check, if any value changed for this class and then calculate the sum.
$( ".amount" ).change(function (){
var sum=0;
$('.amount').each(function(i, obj){
if($.isNumeric(this.value)) {
sum += parseFloat(this.value);
}
})
$('#expence').val(sum);
});
>>Demo<<
Try the below code, it will work for dynamic elements too, just ensure that they have class name amount:
$(".amount").on('change', calculate);
function calculate() {
var sum = 0;
$('.amount').each(function(i, obj) {
if ($.isNumeric(this.value)) {
sum += parseFloat(this.value);
}
});
$('#expense').val(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Amount : <input type="text" class="amount"><br/> Amount : <input type="text" class="amount"><br/> Amount : <input type="text" class="amount"><br/> Expense : <input type="text" id="expense">
I think I got problem with js and html (bootstrap),
I got these snippet from bootsnip and try to modified it for need of my job.
but on the third lines, sorry for typo or bad using english.
the bootsnip here (my modification) : http://bootsnipp.com/snippets/o8r0G
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='name"+i+"' type='text' placeholder='Name' class='form-control input-md' /> </td><td><input name='mail"+i+"' type='text' placeholder='Mail' class='form-control input-md'></td><td><select class='form-control' name='slct"+i+"' placeholder='Select'><option value='1'>1</option><option value='2'>2</option></select></td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
$('.buttonx').click(function() {
var total = 0;
$('#tab_logic tbody tr').each(function(index) {
var price = parseInt($(this).find('.optx sltx option value').text());
var quantity = parseInt($(this).find('.optx sltx option').val());
var value = $(this).find('.value');
var subTotal = price * quantity;
value.text(subTotal);
value.text(price);
total = total + subTotal;
testotal = price;
});
$('.totality').text('Total : '+testotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Value1
</th>
<th class="text-center">
Value2
</th>
<th class="text-center">
Select
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input type="text" name='va10' placeholder='Val1' class="form-control"/>
</td>
<td>
<input type="text" name='va20' placeholder='Val2' class="form-control"/>
</td>
<td class="optx">
<select class="form-control sltx" name="slct0" placeholder="Select"><option value="1">1</option><option value="2">2</option></select>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><a id="buttonx" class="btn btn-default btn-danger pull-right">Calculate</a></th>
<th id="totality" style="vertical-align: middle;">Total : </th>
</tr>
</tfoot>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
I'm trying to create the total from the table but I can't load the value from table with js, maybe I got wrong on the script which I got from other answer on stack. Reference is here : getting values from a html table via javascript/jquery and doing a calculation
I want to ask, how can I got the calculation from select option on table, alternatively from input textbox and without I push the button (real time calculation).
Thanks before.
Well, as per my understand-ability, you need a real time calculator, which calculate value as user entering and leave any textbox or change the select without using the calculate button.
In your code there are some error, I have built and change some of your function to implement the real time calculator. calculation formula is different because I am not able to understand how you are going to calculate. I am implementing it using the class selector of the element and fetching the value with the use of this.
Here is the updated code which is using both, on click button and also real time calculator.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Value1
</th>
<th class="text-center">
Value2
</th>
<th class="text-center">
Select
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input type="text" name='va10' placeholder='Val1' class="form-control va10"/>
</td>
<td>
<input type="text" name='va20' placeholder='Val2' class="form-control va20"/>
</td>
<td class="optx">
<select class="form-control sltx slct0" name="slct0" placeholder="Select"><option value="1">1</option><option value="2">2</option></select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><a id="buttonx" class="btn btn-default btn-danger pull-right">Calculate</a></th>
<th id="totality" style="vertical-align: middle;">Total : </th>
</tr>
</tfoot>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#tab_logic').append("<tr id='addr"+i+"'><td>"+ (i+1) +"</td><td><input name='name'"+i+" type='text' class='form-control va10' placeholder='Name' class='form-control input-md' /> </td><td><input name='mail'"+i+"' type='text' placeholder='Mail' class='va20 form-control input-md'></td><td><select class='form-control slct0' name='slct'"+i+" placeholder='Select'><option value='1'>1</option><option value='2'>2</option></select></td></tr");
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
function calculator(){
var total = 0;
$('#tab_logic tbody tr').each(function(index) {
var val1 = $(this).find('.va10').val().length==0?0:parseInt($(this).find('.va10').val());
var val2 = $(this).find('.va20').val().length==0?0:parseInt($(this).find('.va20').val());
var select = $(this).find('.slct0').val().length==0?0:parseInt($(this).find('.slct0').val());
var subTotal = (val1 + val2)*select;
total+=subTotal;
});
$('#totality').text(total);
}
$('#tab_logic').on('blur change','.va10,.va20,.slct0',function(){
calculator()
})
$('#buttonx').click(function() {
calculator();
});
</script>
This is the code , when you select the opt1 the opt2 will change appropriate. But in the newly added row ( row will add when you click on the Add row button)., is not generating the proper options in opt2.
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="http://web-86d95219-b398-4432-85a8-fae716ac3a54.runnablecodesnippets.com/css/datepicker.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://web-86d95219-b398-4432-85a8-fae716ac3a54.runnablecodesnippets.com/js/bootstrap-datepicker.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Name
</th>
<th class="text-center">
Mail
</th>
<th class="text-center">
Mobile
</th> <th class="text-center">
Mobile
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input id = "date0" type="text" name='name0' placeholder='Name' class="form-control"/>
</td>
<td>
<input type="text" name='mail0' placeholder='Mail' class="form-control"/>
</td>
<td>
<select name="category" class="input category"> <option value = "Week">Week</option>
<option selected value = "Month">Month</option>
<option value = "Year">Year</option></select>
</td><td>
<select name="sub_category" class="input sub_category"></select>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
<script>
$(document).ready(function(){
var i=1;
$(document).on("click", "#add_row", function(){
var datepic = "#date" + i;
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input id = 'date"+
i+"' name='name" + i +
"' type='text' placeholder='Name' class='form-control input-md'/>"
+ "</td><td><input name='mail" +
i + "' type='text' placeholder='Mail' class='form-control input-md'>"
+"</td><td><select class='input category'><option value ='Week'>Week</option><option value = 'Month'>Month</option><option value ='Year'>Year</option></select></select>"
+"</td>"+"</td><td><select class='input sub_category'></select>"
+"</td>");
$(datepic).datepicker();
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$(document).on("click","#delete_row", function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
$(document).on("click",".category", function(){
var new_category = $(".category").val();
var temp = '{"Week": ["2014-02-24", "2014-02-17", "2011-01-03"], "Month": ["Feb 2014", "Apr 2011", "Jan 2011"], "Year": [2014, 2013, 2012, 2011]}';
temp = JSON.parse(temp);
$(".sub_category").find('option').remove();
$.each(temp,function(key, value)
{
if (key == new_category) {
var sub_cats = value.toString().split(',');
for(var i=0;i<sub_cats.length;i++)
{
$(".sub_category").append('<option value= "' + sub_cats[i] + '">' + sub_cats[i] + '</option>');
}
}
});
});
});
$(function() {
var startDate = new Date(2015,2,30);
$('#date0').datepicker('setDate',startDate);
});
</script>
</body>
</html>
Thanks in advance
The problem is the category handler, which need to listen to change event not click event.
Also you need to find the subcategory element which is in the same row
$(document).on("change", ".category", function() {
var new_category = $(this).val();
var temp = '{"Week": ["2014-02-24", "2014-02-17", "2011-01-03"], "Month": ["Feb 2014", "Apr 2011", "Jan 2011"], "Year": [2014, 2013, 2012, 2011]}';
temp = JSON.parse(temp);
var $sub = $(this).closest('tr').find(".sub_category");
$sub.find('option').remove();
$.each(temp, function(key, value) {
if (key == new_category) {
var sub_cats = value.toString().split(',');
for (var i = 0; i < sub_cats.length; i++) {
$sub.append('<option value= "' + sub_cats[i] + '">' + sub_cats[i] + '</option>');
}
}
});
});
Demo: Fiddle
Just change your jquery with $(this), to make the changes only with the respective tr's sub category not with all.
$(document).ready(function(){
var i=1;
$(document).on("click", "#add_row", function(){
var datepic = "#date" + i;
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input id = 'date"+
i+"' name='name" + i +
"' type='text' placeholder='Name' class='form-control input-md'/>"
+ "</td><td><input name='mail" +
i + "' type='text' placeholder='Mail' class='form-control input-md'>"
+"</td><td><select class='input category'><option value ='Week'>Week</option><option value = 'Month'>Month</option><option value ='Year'>Year</option></select></select>"
+"</td>"+"</td><td><select class='input sub_category'></select>"
+"</td>");
$(datepic).datepicker();
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$(document).on("click","#delete_row", function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
$(document).on("change",".category", function(){
$this = $(this);
var new_category = $this.val();
var temp = '{"Week": ["2014-02-24", "2014-02-17", "2011-01-03"], "Month": ["Feb 2014", "Apr 2011", "Jan 2011"], "Year": [2014, 2013, 2012, 2011]}';
temp = JSON.parse(temp);
$this.parents('tr').find(".sub_category").find('option').remove();
$.each(temp,function(key, value)
{
if (key == new_category) {
var sub_cats = value.toString().split(',');
for(var i=0;i<sub_cats.length;i++)
{
$this.parents('tr').find(".sub_category").append('<option value= "' + sub_cats[i] + '">' + sub_cats[i] + '</option>');
}
}
});
});
});
$(function() {
var startDate = new Date(2015,2,30);
$('#date0').datepicker('setDate',startDate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Name
</th>
<th class="text-center">
Mail
</th>
<th class="text-center">
Mobile
</th> <th class="text-center">
Mobile
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input id = "date0" type="text" name='name0' placeholder='Name' class="form-control"/>
</td>
<td>
<input type="text" name='mail0' placeholder='Mail' class="form-control"/>
</td>
<td>
<select name="category" class="input category"> <option value = "Week">Week</option>
<option selected value = "Month">Month</option>
<option value = "Year">Year</option></select>
</td><td>
<select name="sub_category" class="input sub_category"></select>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>