Error inserting multi row values with a form - javascript

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>

Related

How to populate dropdown data from one dropdown to another dropdown?

I have two dropdowns one is outside of dynamic table another one is inside of table column. now my problem is how to populate non-selected data one dropdown to another dropdown.
Which means, for example if i select one value from 1st dropdown, remaining non selected values only Copied to 2nd dropdown (inside dynamic table dropdown). and if i click add row, that same 2nd dropdown data will come dynamically added rows.
i hope my question is understandable.
here is my Example Fiddle
Faild Fiddle Here
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr' + i).html("<td><input name='cashpayment[" + i + "].name' type='text' placeholder='Enter code' id='cashacc_code' class='form-control input-md'/></td><td><select class='form-control input-md' name='cashpayment[" + i + "].name' id='dynamic_sel'><option>Second dropdown</option></select></td><td><input name='cashpayment[" + i + "].name' type='text' placeholder='Enter your text here' class='form-control input-md' id='acc_narrat' data-toggle='modal' data-target='#accnarratModal' /> </td><td><input name='cashdebt[" + i + "].name' type='text' placeholder='Amount 1' class='form-control input-md' id='cashdeb'data-action='sumDebit'></td><td><input name='cashcredit[" + i + "].name' type='text' placeholder='Amount 2' data-action='sumCredit' class='form-control input-md' readonly></td>");
// {/* <td>" + (i + 1) + "</td> */}
$("#cashacc_sel").find("select").append().appendTo($("#dynamic_sel"));
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
// $('#cashacc_sel').append($('#dynamic_sel').html());
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});
<div class="form-group col-4" style="margin-bottom: 20px;">
<label class="col-sm-12 control-label p-sm-0 input-group"> First Dropdown:</label>
<select class="form-control selectsch_items" name="cashacc" id="cashacc" required>
<option value="">Choose an items</option>
<option value="acc1">joe 1</option>
<option value="acc2">joe 2</option>
<option value="acc3">joe 3</option>
</select>
</div>
<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 style="background-color: #680779; color: #fff;">
<th class="text-center">
Code
</th>
<th class="text-center">
Name*
</th>
<th class="text-center">
Text*
</th>
<th class="text-center">
Initial amount*
</th>
<th class="text-center">
First Payment
</th>
</tr>
</thead>
<tbody>
<a id="add_row" class="btn btn-default pull-left adRow">Add Row</a><a id='delete_row' class="pull-right btn btn-default adRow" style="margin-right: 5px;">Delete Row</a>
<tr id='addr0'>
<td>
<input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter Code' class="form-control" />
</td>
<td>
<select class="form-control" name="cashacc_sel" id="cashacc_sel">
<option value="">Second dropdown</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter your text here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" id="cashdeb" name='cashdebt' placeholder='Amount 1' data-action="sumDebit" class="form-control" />
</td>
<td>
<input type="number" id="cashcredit" name='cashcredit' placeholder='Amount 2' data-action="sumCredit" class="form-control" readonly />
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
</div>
Please check this link Clik for more details
Html Code
<div class="form-group col-4" style="margin-bottom: 20px;"> <label class="col-sm-12 control-label p-sm-0 input-group"> First Dropdown:</label> <select class="form-control selectsch_items" name="cashacc" id="cashacc" required>
<option value="">Choose an items</option>
<option value="acc1">joe 1</option>
<option value="acc2">joe 2</option>
<option value="acc3">joe 3</option> </select> </div>
<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 style="background-color: #680779; color: #fff;">
<th class="text-center">
Code
</th>
<th class="text-center">
Name*
</th>
<th class="text-center">
Text*
</th>
<th class="text-center">
Initial amount*
</th>
<th class="text-center">
First Payment
</th>
</tr>
</thead>
<tbody>
<a id="add_row" class="btn btn-default pull-left adRow">Add Row</a><a id='delete_row' class="pull-right btn btn-default adRow" style="margin-right: 5px;">Delete Row</a>
<tr id='addr0'>
<td>
<input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter Code' class="form-control" />
</td>
<td>
<select class="form-control" name="cashacc_sel" id="cashacc_sel">
<option value="">Second dropdown</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter your text here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" id="cashdeb" name='cashdebt' placeholder='Amount 1' data-action="sumDebit" class="form-control" />
</td>
<td>
<input type="number" id="cashcredit" name='cashcredit' placeholder='Amount 2' data-action="sumCredit" class="form-control" readonly />
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div> </div> </div>
Jquery Code
$(document).ready(function() {
$("#cashacc_sel").html($('#cashacc').html());
var i = 1;
$("#add_row").click(function() {
var oSelectedValue = $('#cashacc').val();
$('#addr' + i).html("<td><input name='cashpayment[" + i + "].name' type='text' placeholder='Enter code' id='cashacc_code' class='form-control input-md'/></td><td><select class='form-control input-md' name='cashpayment[" + i + "].name' id='dynamic_sel'><option>Second dropdown</option></select></td><td><input name='cashpayment[" + i + "].name' type='text' placeholder='Enter your text here' class='form-control input-md' id='acc_narrat' data-toggle='modal' data-target='#accnarratModal' /> </td><td><input name='cashdebt[" + i + "].name' type='text' placeholder='Amount 1' class='form-control input-md' id='cashdeb'data-action='sumDebit'></td><td><input name='cashcredit[" + i + "].name' type='text' placeholder='Amount 2' data-action='sumCredit' class='form-control input-md' readonly></td>");
// {/* <td>" + (i + 1) + "</td> */}
$("#cashacc_sel").find("select").append().appendTo($("#dynamic_sel"));
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
// $('#cashacc_sel').append($('#dynamic_sel').html());
$("select[name='cashpayment[" + i + "].name']").html($('#cashacc option:not(:selected)'));
$("#cashacc").html($('#cashacc_sel').html());
$("#cashacc").val(oSelectedValue);
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});

How to Fix the Code In Order to lets the Function Working

I'm getting a django project to fix the error inside the code, may I know what is the problem of this few line of code which cause the add and delete button on the webpage does not function well?
I've tried fixing some typo error in the code, but it's still not working so I'm changing back the code to it's original way.
{% extends "app/layout.html" %}
{% block content %}
<script>
$(document).ready(function () {
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input
name='item_id' type='item_id' placeholder='Item ID'
class='form-control input-md' /> </td><td><input
name='item_name' type='text' placeholder='Item Name'
class='form-control input-md'></td><td><input
name='description' type='text' placeholder='Description'
class='form-control input-md' ></td><td><input name='quantity'
type='text' placeholder='Quantity' class='form-control input-
md' /> </td><td><input name='unit_price' type='text'
placeholder='Price Per Unit' class='form-control input-md' />
</td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$('#addr'+(i-1)).html('');
i--;
}
});
});
</script>
<div class="formpurchaseorder margintop" >
<form class="purchaseordersubmission"
action="purchaserequisitionconfirmation" method="POST">
{% csrf_token %}
<div class="row margintop">
<div class="col">
<input type="text" class="form-control" name="purchase_requisition_id" value="{{purchase_requisition_id}}" placeholder="Purchase Requisition ID" readonly>
</div>
<div class="col">
<input type="text" class="form-control" name="person_id" id="person_id" value="{{person_id}}"placeholder="Person ID" readonly>
</div>
</div>
<br/>
<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">Item ID</th>
<th class="text-center">Item Name</th>
<th class="text-center">Description</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price Per Unit</th>
</tr>
</thead>
<tbody name="item_rows">
<tr id='addr'>
<td>1</td>
<td> <input type="text" name='item_id' placeholder='Item id' class="form-control" /> </td>
<td><input type="text" name="item_name" placeholder='Item name' class="form-control" ></td>
<td><input type="text" name='description' placeholder='Description' class="form-control" /></td>
<td><input type="text" name='quantity' placeholder='Quantity' class="form-control" /></td>
<td><input type="text" name='unit_price' placeholder='Price Per Unit' class="form-control" /></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<a id='add_row' class="pull-left btn btn-default">Add Item</a>
<a id='delete_row' class="pull-right btn btn-default">Delete Item</a>
<div class="margintop">
<button type="submit" class="btn btn-success btn-square buttonsize">Submit</button>
<a class="btn btn-danger btn-square buttonsize" href="/menu">Cancel</a>
</div>
</form>
</div>
{% endblock %}
Variables like item_id will only be available to you when you submit the form and then you'll be redirected to a URL with all the variables posted on it.
Eg. localhost:8000/index.html?item_id=xyz&item_name=abc&description=desc&quantity=12&unit_price=30
Notice the variable name with their values in the URL. This will only be available after you submit the form.
So Instead of adding the event listener on add_row, use :
$('#formid').submit(function(e) {
// Add the rows here
});
PS:- If you really want to do it this way, then you can get the text box values by :
First giving an ID to the input text box :
<input type="text" id='item_name_textbox' name='item_id' placeholder='Item id' class="form-control" /> </td>
var item_name = document.getElementById('item_name_textbox').value;
and then using it in your function.
looks like your script is loaded before the HTML fully rendered and perhaps jQuery.
Try to put this script section at the end of your <body> (eventually in app/layout.html).
After the jQuery implementation.

calculate select option value on table with jquery

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>

jQuery dynamic functions with variable params

I'm trying to make a little program that uses generated (dynamically) tables, I will explain an example:
I have a blank page with only and input (number type) and a div:
<input id='numoftables' type='number'>
<div id='tablescontainer'></div>
I need create N tables with the following structure:
<table>
<tr>
<td>
<div style='text-align:left;'>
<h3>
<span class='label label-default'>Table #N</span>
</h3>
</div>
</td>
<td>
<input id='secondNum' type='number' class='form-control input-md' value='1'>
</td>
</tr>
</table>
<div class='table-responsive text-left'>
<table id='tableN' class='table table-striped condensed'>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
<th>Col 6</th>
</tr>
</thead>
<tbody>
<tr>
<td align='middle'>
<b>M</b>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<div class='input-group date' id='fecha'>
<input id='fechainput' maxlength='10' data-date-format='DD/MM/YYYY' type='date' class='form-control' placeholder='Fecha DD/MM/AAAA' required>
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'></span>
</span>
</div>
</td>
<td align='middle'>
<img class='delete' src='img/delete.png' >
</td>
</tr>
</tbody>
</table>
</div>
<hr>
It's generate something similar of this (with setting a value of 3 on input with id 'numoftables'):
But I want to make dynamic elements (with dynamic id's), please see this:
Red boxes will have the dynamic number, 1 to N; N is the value of the input with id 'numoftables'.
Green boxes represents the numbers of rows (I call this number, M) of the tableN.
How can I to generate all of this dynamically :(?
I have a crazy code, like this:
$("#tablescontainer").html(null);
for (i=1;i<=$("#numoftable").val();i++)
{
$("#tablescontainer").append("<table><tr><td><div style='text-align:left;'><h3><span class='label label-default'>Table #N</span></h3></div></td><td style='position:relative;top:7px !important;left:8px;'><input id='secondNum' type='number' style='width:64px;' class='form-control input-md' value='1'></td></tr></table><div class='table-responsive text-left'><table id='tableN' class='table table-striped condensed'><thead><tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th><th>Col 6</th></tr></thead><tbody><tr><td align='middle'><b>M</b></td><td><input type='number' class='form-control input-md'></td><td><input type='number' class='form-control input-md'></td><td><input type='number' class='form-control input-md'></td><td><div class='input-group date' id='fecha'><input id='fechainput' maxlength='10' data-date-format='DD/MM/YYYY' type='date' class='form-control' placeholder='Fecha DD/MM/AAAA' required><span class='input-group-addon'><span class='glyphicon glyphicon-calendar'></span></span></div></td><td align='middle'><img width='20' class='delete' src='img/delete.png' ></td></tr></tbody></table></div><hr><script>$('#numcarr"+i+"').click(function(e){$('#tabla"+i+" > tbody:last').html(null);for (j=1;j<=$(\"#numcarr"+i+"\").val();j++){$('#tabla"+i+" > tbody:last').append('<tr><td align=\"middle\"><b>"+i+"</b></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><div class=\"input-group date\" id=\"fecha\"><input id=\"fechainput\" maxlength=\"10\" data-date-format=\"DD/MM/YYYY\" type=\"date\" class=\"form-control\" placeholder=\"Fecha DD/MM/AAAA\" required><span class=\"input-group-addon\"><span class=\"glyphicon glyphicon-calendar\"></span></span></div></td><td align=\"middle\"><img width=\"20\" class=\"delete\" onclick=\"$(this).parent().parent().remove()\" src=\"img/delete.png\"></td></tr>')}});</script>");
}
I don't know how can I solve this, write less code, make it dynamically :c
Thanks!
see the result in by inspect the table and secondNum: jsfiddle
jQuery
$(function(){
$("#numoftables").on("change", function(){
$("#tablescontainer").html("");
var num = $(this).val();
var table = $("#copy").html();
for (var i=1; i <= num; i++){
var newTable = table.replace("secondNum", "id='secondNum"+i).replace("uniqueTable", "uniqueTable"+i);
$("#tablescontainer").append(newTable);
}
});
});
CSS
#copy{
display: none;
}
Now you have to do other things in the similar fashion, like showing
the the table number. use a different id which may not use in the
content and replace it in the jquery.

Onclick event is not working in new added rows

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>

Categories