Getting the values from dynamicly created input(s) from a table - javascript

I have a table
<form id="project-form">
<table id="project-table" class="table table-striped table-inverse table-responsive">
<caption>Projects</caption>
<thead class="thead-inverse">
<tr>
<th scope="col">#</th>
<th scope="col">Project name</th>
<th scope="col">Description</th>
<th scope="col">Estimated time (min)</th>
<th scope="col">Actual time (min)</th>
<th scope="col">Add task</th>
<th scope="col">Delete project</th>
</tr>
</thead>
<tbody id="project-body">
</tbody>
</table>
</form>
This table is filled with data from an AJAX GET request
function getProjects() {
$.ajax({
method: 'GET',
dataType: 'json',
data: {
functionToCall: 'project',
},
url: 'http://localhost/WBS/php/api/requests/get.php',
success: (response) => {
$.each(response, function () {
$.each(this, function (index, value) {
$('#project-body').append(
`
<tr>
<td>
<input class="form-control" type="hidden" name="projectid" id="projectid" value="${value.projectid}">
</td>
<td>
<input class="form-control" type="text" name="projectName" id="projectName" value="${value.title}">
</td>
<td>
<input class="form-control" type="text" name="description" id="description" value="${value.description}">
</td>
<td>
<input class="form-control" type="text" name="estimatedTime" id="estimatedTime" value="${value.Estimated_time}">
</td>
<td>
<input class="form-control" type="text" name="actualTime" id="actualTime" value="${value.Actual_time}">
</td>
<td>
<a id="addTask" class="btn btn-info" href="Overview.html?id=${value.projectid}" role="button">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Add task
</a>
</td>
<td>
<button type="button" id="deleteProject" name="deleteProject" class="btn btn-danger">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
</button>
</td>
</tr>
`
);
});
});
},
error: () => {
console.error('Something went wrong with the getProjects function');
},
});
}
There is also the option to dynamically add a new row of inputs to the table
function addProject() {
event.preventDefault();
$('#project-body').append(
`
<tr>
<td>
<input class="form-control" type="hidden" name="projectid" id="projectid" >
</td>
<td>
<input class="form-control" type="text" name="projectName" id="projectName">
</td>
<td>
<input class="form-control" type="text" name="description" id="description">
</td>
<td>
<input class="form-control" type="text" name="estimatedTime" id="estimatedTime">
</td>
<td>
<input class="form-control" type="text" name="actualTime" id="actualTime">
</td>
<td>
<a id="addTask" class="btn btn-info" href="Overview.php" role="button">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Add task
</a>
</td>
<td>
<button type="button" id="deleteProject" name="deleteProject" class="btn btn-danger">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
</button>
</td>
</tr>
`
);
}
I submit all of my data on this button
<button id="saveProjects" form="project-form" class="btn btn-info" type="button"><i class="fa fa-angle-right" aria-hidden="true"></i> Save changes</button>
In the document ready I handle all of my onclick events
$(document).ready(() => {
$('#saveProjects').on('click', () => {
uploadProjects();
});
$('#addProject').on('click', () => {
addProject();
});
});
On my PHP side I have a class that handles all of my POST requests, inside of this class is a function that will handle the uploading of new projects
public function uploadProject()
{
try {
$title = $_POST["projectName"];
$description = $_POST["description"];
$estimatedTime = $_POST["estimatedTime"];
$actualTime = $_POST["actualTime"];
$stm = $this->pdo->getCon();
$PDOStatement = $stm->prepare("INSERT INTO projects (title,description,Estimated_time,Actual_time) VALUES(:title,:description,:Estimated_time,:Actual_time)");
$PDOStatement->bindParam(':title', $title, PDO::PARAM_STR);
$PDOStatement->bindParam(':description', $description, PDO::PARAM_STR);
$PDOStatement->bindParam(':Estimated_time', $estimatedTime, PDO::PARAM_STR);
$PDOStatement->bindParam(':Actual_time', $actualTime, PDO::PARAM_STR);
$PDOStatement->execute();
header('HTTP/1.1 200 OK');
} catch (Exception $th) {
header("HTTP/1.0 404 Not Found");
throw $th->getMessage();
}
}
Now debugging my PHP code, and all the data I receive in the POST array will always correspond to the first row in the table, for example:
Let's say i have a existing row inside of my table with the values of : Project name = Hello | Description = World.
I click on the add project button and a new row is added to the table, I fill in the inputs inside of the row with something like this : Project name = Second table row | Description = Second description.
At the back-end I will always receive the values of Hello and World and not the values of the newest added row inside of the table.
I googled around a bit and only saw examples on how to the value of a SINGLE dynamically added input and not a new row.

I think you can rename your inputs like:
name="projectid[]"
Then PHP will receive an array of those values:
$total = count($_POST["projectid"]);
for ($i = 0; $i < $total; $i++) {
$title = $_POST["projectName"][$i];
$description = $_POST["description"][$i];
$estimatedTime = $_POST["estimatedTime"][$i];
$actualTime = $_POST["actualTime"][$i];
// Your INSERT query is performed here
}

Related

Laravel, javascript add rows table class select not working

I have this code which works fine. my problem is that when i go to add one or more rows in the table with the button
the select:
<select name = "product_id_product []" id = "product_id_product '. $ request-> count_product.'" class = "form-control js-select2" required>
it is as if it does not take the "js-select2" class
if instead I insert it manually in the index bypassing the whole class it works
I just can't figure out how to do it ..
index.blade:
<div class="card-body" style="text-align: center;">
<button type="button" name="aggiungi_prodotto" id="aggiungi_prodotto" class="btn btn-primary aggiungi_prodotto" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Prodotto</button>
<button type="button" name="aggiungi_accessorio" id="aggiungi_accessorio" class="btn btn-success aggiungi_accessorio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Accessorio</button>
<button type="button" name="aggiungi_servizio" id="aggiungi_servizio" class="btn btn-warning aggiungi_servizio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Servizio</button>
<button type="button" name="aggiungi_riga" id="aggiungi_riga" class="btn btn-danger aggiungi_riga" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Riga</button> <br/><br/><br/>
<div class="form-row">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th width="50%">Prodotto</th>
<th width="10%">Quantità</th>
<th width="10%">Acconto</th>
<th width="10%">Costo</th>
<th width="10%">Sconto TOT</th>
<th width="10%">Azioni</th>
</tr>
</thead>
<tbody id="prodottiRows">
</tbody>
</table>
</div>
</div>
<hr>
</div>
Javascript:
var count_prodotto = 0;
$(document).on('click', '#aggiungi_prodotto', function(){
count_prodotto = count_prodotto + 1;
var categorieID = document.getElementById('categorie_id').value;
var brandID = document.getElementById('brand_id').value;
var modelloID = document.getElementById('modello_id').value;
$.ajax({
type: 'POST',
url: "{{ route('autocomplete.fetch_prodotti') }}",
data: {
'_token': $('input[name=csrf-token]').val(),
'categorie_id':categorieID,
'brand_id':brandID,
'modello_id':modelloID,
'count_prodotto':count_prodotto
},
success:function(data){
$('#prodottiRows').append(data);
}
});
});
Controller:
public function fetch_prodotti(Request $request)
{
$products = Product::with('Multitenantable')
->where("stato_prodotto",'1')
->where("categorie_id",$request->categorie_id)
->where("brand_id",$request->brand_id)
->where("modello_id",$request->modello_id)
->pluck("nome_prodotto","id");
$prodotti = '
<tr id="row_prodotto'.$request->count_prodotto.'">
<td><select name="product_id_prodotto[]" id="product_id_prodotto'.$request->count_prodotto.'" class="form-control js-select2" required>
<option value="">Seleziona Prodotto</option>';
foreach ($products as $key => $product) {
$prodotti .= '<option value="'.$key.'">'.$product.'</option>';
# code...
}
$prodotti .='</select></td>
<td><input type="text" name="quantita_prodotto[]" id="quantita_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="acconto_prodotto[]" id="acconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="costo_prodotto[]" id="costo_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="sconto_prodotto[]" id="sconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td data-column="Rimuovi"><button type="button" name="remove_prodotto" id="'.$request->count_prodotto.'" class="btn btn-danger btn-xs remove_prodotto">Rimuovi</button></td>
</tr>';
return response()->json($prodotti);
}

Column cannot be null by using Auth

I'm inserting multiple data into the database. There is an error for my column report_by which is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'report_by' cannot be null (SQL: insert into 'complaints' ('defect_id', 'image', 'description', 'report_by') values (1, C:\wamp64\tmp\php8E2E.tmp, leak, ?)) Inside column report_by should be the id of the user by using Auth. It's to tell that the complaint made by which users.
users table
id
role
email
typable_id
typable_type
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Complaint;
use Illuminate\Http\Request;
class ComplaintController extends Controller
{
public function index()
{
return view('buyers.complaint');
}
public function create(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $request->image[$item],
'description' => $request->description[$item],
'report_by' => $request->user_id,
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
}
complaint.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>Make New Report</strong></h3>
</div>
<div class="panel-body">
<div>
<div class="panel">
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</form>
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
Here my javascript inside the blade
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += ' <td><input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}"><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += ' <td><input type="file" class="form-control-file" name="image[]"></td>';
html += ' <td><input type="text" class="form-control" name="description[]"></td>';
html += ' <td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop

Add button not show after show data

After ajax success, data show in rows but if I want to add a new row at that time add button not shows.
My code:
<div class="row">
<div class="col-12">
<h3>Add Video Detail</h3>
<form id="insertvideo" method="post">
<table id="addrow" width="100%">
<td><input type="button" class="btn btn-success addButton col-3 offset-1" value="add"/></td>
<tr class="clonetr">
<td>Video Title<input type="text" id="videotitle" name="videotitle[]" class="form-control"></td>
<td>Video description<input type="text" id="videodesc" name="videodesc[]" class="form-control"></td>
<td>Video Links<input type="text" id="videolink" name="videolink[]" class="form-control"></td>
<td><input type="button" class="btn btn-danger deleteButton" value="delete"/></td>
</tr>
</table>
</form>
</div>
</div>
<div class="col-sm-6" style="margin-top: 13px; margin-left: 400px;">
<button type="submit" id="btn-update" value="Submit" class="btn btn-primary col-3 offset-1">Save</button>
</div>
<script>
$(function(){
$(".addButton").click(function(){
$('.clonetr:last').clone(true).appendTo("#addrow");
});
$(".deleteButton").click(function(){
if($('.deleteButton').length > 1)
$(this).closest("tr").remove();
else
alert('Atleast one required.');
});
});
var mainCatId = $(this).val();
$.ajax({
url: "<?php echo base_url();?>admin_controller/WebsiteContentController/fetchSubDetail",
type: "POST",
data: {mainCatId:mainCatId},
dataType:'html',
success: function(response)
{
$('#addrow').html(response);
console.log(response);
}
});
</script>
I do not know where I am wrong in my code.
I want to add a new row but add button show to add a new row.
Since I can't run your ajax, this will only be a guess on how to fix it.
First, fix the table by adding the missing <tr>:
<table id="addrow" width="100%">
<tr>
<td><input type="button" class="btn btn-success addButton col-3 offset-1" value="add" /></td>
</tr>
<tr class="clonetr">
<td>Video Title<input type="text" id="videotitle" name="videotitle[]" class="form-control"></td>
<td>Video description<input type="text" id="videodesc" name="videodesc[]" class="form-control"></td>
<td>Video Links<input type="text" id="videolink" name="videolink[]" class="form-control"></td>
<td><input type="button" class="btn btn-danger deleteButton" value="delete" /></td>
</tr>
</table>
Now to clear the table but leave the add button:
$('#addrow tr:not(:first)').remove();
$('#addrow').append(response);
So now it looks like:
$.ajax({
url: "<?php echo base_url();?>admin_controller/WebsiteContentController/fetchSubDetail",
type: "POST",
data: {mainCatId:mainCatId},
dataType:'html',
success: function(response)
{
$('#addrow tr:not(:first)').remove();
$('#addrow').append(response);
console.log(response);
}
});
To clear the newly created row, try with:
$(".addButton").click(function(){
$('.clonetr:last').clone(true).appendTo("#addrow");
$("#addrow tr:last input").val("");
});
// addd for Vendor Origin in admin zone
$(".addorigin").on("click", function (e){
$('.origintable tr:last').before('<tr class="origindiv"> <td > <input type="text" /><i class="fa fa-question-circle info" data-toggle="tooltip" data-placement="top" title="Sender Number."></i></td><td ><input type="text" /><i class="fa fa-question-circle info" data-toggle="tooltip" data-placement="top" title="Enter sender name."></i></td> <td><div class="rorigin"><i class="fa fa-minus-circle" aria-hidden="true"></i></div></td> </tr>');
});
//remove row
$('.origintable').on('click','.removeorigin',function() {
$(this).closest("tr.origindiv").remove();
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<table class="text-center origintable">
<tr class="origindiv">
<td >
<input type="text" /><i class="fa fa-question-circle info" data-toggle="tooltip" data-placement="top" title="Sender Number."></i>
</td>
<td >
<input type="text" /><i class="fa fa-question-circle info" data-toggle="tooltip" data-placement="top" title="Enter sender name."></i>
</td>
</tr>
</table>
<i class="fa fa-plus-circle"></i> Add More Row
In your ajax success function, you added a code like this.
$('#addrow').html(response);
html() function will replace everything inside your addrow element. so the add button will be replaced with your response data. please use add button in separate section or add a new container to append the response data.

multi ng -repeat and remove rows in angular js

I'm new to AngularJs and I'm stuck in multi ng-repeat.
HTML CODE
<table class="table table-bordered tdPaddingNull verTop">
<thead>
<tr>
<th width="200px">Product Details </th>
<th width="250px">Current Availability</th>
<th width="200px">Batch </th>
<th>Quantity</th>
<th>Rate INR </th>
<th>Amt. INR</th>
<th>Converted Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(i,product) in listproducts track by $index">
<td style="padding: 7px;">
<input auto-complete ui-items="prductdetail" ng-model="formData.product_name[i]" class="form-control form-white" my-id="{{i}}"/>
<input id="product_id{{i}}" placeholder="productid" type="hidden" value="" ng-model="formData.product_id[i]" my-id="{{i}}"/>
<a ng-click="addProductBatch()" title="Add Another Batch Quantity" style="float:right;"><i class="fa fa-plus" aria-hidden="true"></i> ADD BATCH </a>
</td>
<td class="line-item-column item-currentavail transferorder-lineitem">
<div class="row text-muted font-sm">
<div class="col-md-6">
Source Stock
</div>
<div class="separationline col-md-6">
Destination Stock
</div>
</div>
<div class="row font-xs">
<div class="col-md-6">
0.00 Units
</div>
<div class="separationline col-md-6">
0.00 Units
</div>
</div>
</td>
<td style="padding: 7px;">
<div style="display:inline-block;width:100%;" ng-repeat="addBatch in listAddbatches">
<select class="form-control form-white selectNor" ng-model="formData.batch_id[i]" ng-change="changedBatchValue(formData.batch_id)" style="margin-bottom: 5px;width: 88%;float: left;">
<option value="">Select Batch</option>
<option value="{{blist.batch_id}}" ng-repeat="blist in batchList">{{blist.batch_number}}</option>
</select>
<a class="inputTabel1" ng-click="removeBatch($index)" title="Remove Batch" style="float:left;margin-left: 4px;"> <i class="fa fa-times-circle-o" aria-hidden="true" ></i>
</a>
</div>
</td>
<td style="padding: 7px;">
<input class="form-control form-white" type="text" value="" ng-model="formData.product_count[i]" ng-repeat="addBatch in listAddbatches" style="margin-bottom: 5px;"/>
</td>
<td style="padding: 7px;">
<input class="form-control form-white " placeholder="Selling Price" type="text" value="0.00" ng-model="formData.sel_inr_rate[i]">
</td>
<td>
<input class="form-control form-white form-Tabel" placeholder="Amount in INR" type="text" value="0.00" ng-model="formData.sel_inr_amount[i]" readonly />
</td>
<td class="Amount ">
<input class="form-control form-white form-Tabel" placeholder="" type="text" value="0.00" ng-model="formData.exc_total_amount[i]" readonly />
<button class="inputTabel" ng-click="removeProduct($index)"> <i class="fa fa-times-circle-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
ANGULAR CODE
/****************ADD ANOTHER BATCH QUANTITY**************/
$scope.addAnotherProduct = function(listproducts,$event) {
newItemNo = $scope.listproducts.length+1;
$scope.listproducts.push({'batch_id[newItemNo]':'','product_count[newItemNo]':''});
};
$scope.removeProduct = function(index) {
/*var lastItem = $scope.listproducts.length-1;
$scope.listproducts.splice(lastItem);
$scope.listAddbatches = '';*/
$scope.listproducts.splice(index,1);
};
$scope.removeBatch = function(index) {
/*var lastItem = $scope.listAddbatches.length-1;
$scope.listAddbatches.splice(lastItem);
$scope.listAddbatches = '';*/
$scope.listAddbatches.splice(index,1);
};
$scope.addProductBatch = function() {
var newItemNo = $scope.listAddbatches.length+1;
$scope.listAddbatches.push({'id':'batch'+newItemNo});
};
Here when I click ADD ANOTHER PRODUCT it should create an entire row in the table without the columns of Batch and Quantity, but now it's appearing as it in before row created.
Then when I click ADD BATCH it should create under the table column Batch and Quantity of the corresponding row, but now it's adding in all the rows and when I remove added batch, it should remove the corresponding batch, but now it's removing the last added batch.
The same happens when I remove added product (Entire Row), it should remove the corresponding row of the product but now it's removing lastly added Product row.
How can I fix all the aforementioned issues?
Please help me
There are multiple issues with your approach:
1) You are using a global array listAddbatches but you want to add the batches by product, so why shouldn't you use product.listAddbatches array?
2) When using track by $index you will not able to delete correct element from array or object since compiler directive is not re-compiling the element when its data attribute changes.
3) Using array length to generate id like var newItemNo = $scope.listAddbatches.length + 1; is not a good idea since the array length could change (when removing items) in a way that you will have the same ids for different elements.
4) This line is very strange {'batch_id[newItemNo]':'','product_count[newItemNo]':''}, since you are calculating newItemNo, but this is a simple string 'batch_id[newItemNo]'. Why do you need this?
5) Do not recommend to use $index to remove items, since it could point to some other element in case of filtering.
Your code could like this (simplified version), hope this helps:
angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
$scope.listproducts = [];
$scope.addAnotherProduct = function(listproducts) {
listproducts.push( {
listAddbatches: []
});
};
$scope.removeProduct = function(product) {
var index = $scope.listproducts.indexOf(product);
if (index >= 0)
$scope.listproducts.splice(index, 1);
};
$scope.removeBatch = function(product, batch) {
var index = product.listAddbatches.indexOf(batch);
if (index >= 0)
product.listAddbatches.splice(index, 1);
};
$scope.addProductBatch = function(product) {
product.listAddbatches.push({ });
};
});
<script src="https://code.angularjs.org/1.6.4/angular.js" ></script>
<html ng-app="plunker">
<body ng-controller="MainCtrl">
<table class="table table-bordered tdPaddingNull verTop">
<thead>
<tr>
<th width="200px">Product Details </th>
<th width="250px">Current Availability</th>
<th width="200px">Batch </th>
<th>Quantity</th>
<th>Rate INR </th>
<th>Amt. INR</th>
<th>Converted Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(i, product) in listproducts">
<td style="padding: 7px;">
<input auto-complete ui-items="prductdetail" ng-model="formData.product_name[i]" class="form-control form-white" my-id="{{i}}"/>
<input id="product_id{{i}}" placeholder="productid" type="hidden" value="" ng-model="formData.product_id[i]" my-id="{{i}}"/>
<a ng-click="addProductBatch(product)" title="Add Another Batch Quantity" style="float:right;"><i class="fa fa-plus" aria-hidden="true"></i> ADD BATCH </a>
</td>
<td class="line-item-column item-currentavail transferorder-lineitem">
<div class="row text-muted font-sm">
<div class="col-md-6">
Source Stock
</div>
<div class="separationline col-md-6">
Destination Stock
</div>
</div>
<div class="row font-xs">
<div class="col-md-6">
0.00 Units
</div>
<div class="separationline col-md-6">
0.00 Units
</div>
</div>
</td>
<td style="padding: 7px;">
<div style="display:inline-block;width:100%;" ng-repeat="addBatch in product.listAddbatches">
<select class="form-control form-white selectNor" ng-model="formData.batch_id[i]" ng-change="changedBatchValue(formData.batch_id)" style="margin-bottom: 5px;width: 88%;float: left;">
<option value="">Select Batch</option>
<option value="{{blist.batch_id}}" ng-repeat="blist in batchList">{{blist.batch_number}}</option>
</select>
<a class="inputTabel1" ng-click="removeBatch(product, addBatch)" title="Remove Batch" style="float:left;margin-left: 4px;"> <i class="fa fa-times-circle-o" aria-hidden="true" ></i>
</a>
</div>
</td>
<td style="padding: 7px;">
<input class="form-control form-white" type="text" value="" ng-model="formData.product_count[i]" ng-repeat="addBatch in product.listAddbatches" style="margin-bottom: 5px;"/>
</td>
<td style="padding: 7px;">
<input class="form-control form-white " placeholder="Selling Price" type="text" value="0.00" ng-model="formData.sel_inr_rate[i]">
</td>
<td>
<input class="form-control form-white form-Tabel" placeholder="Amount in INR" type="text" value="0.00" ng-model="formData.sel_inr_amount[i]" readonly />
</td>
<td class="Amount ">
<input class="form-control form-white form-Tabel" placeholder="" type="text" value="0.00" ng-model="formData.exc_total_amount[i]" readonly />
<button class="inputTabel" ng-click="removeProduct(product)"> <i class="fa fa-times-circle-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
<button ng-click="addAnotherProduct(listproducts)">Add Another Product</button>
</body>
</html>

Saving multiple rows with jQuery

I have a form with 2 fields with an add row button. When this button is clicked it simply clones the row and adds another row consisting of the 2 form fields. How do I save these newly added fields in my ajax post? Right now, it only ever saves the last row in my form.
<form action="." method="post">
<table class="table table-condensed" id="pa">
<thead>
<tr>
<th class="col-xs-2">Description</th>
<th class="col-xs-2">Expected %</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<input class="text-box single-line" data-val="true" data-val-required="The Description field is required." id="Description" name="Description" value="" type="text">
</div>
</td>
<td>
<div class="form-group">
<div class="input-group">
<input class="text-box single-line" data-val="true" data-val-number="The field Expected must be a number." id="Expected" name="Expected" value="100" type="number">
</div>
</div>
</td>
<td class="vert-align"> <a class="btn btn-danger btn-xs remove-row-pa">x</a>
</td>
</tr>
</tbody>
</table>
<div class="pull-right">
<p> <a href="#" id="add-pa-row" class="btn btn-success btn-xs">
<i class="fa fa-plus-circle"></i> Add row
</a>
</p>
</div>
<div class="form-group">
<p>
<input value="Save" class="btn btn-success" type="submit">
</p>
</div>
</form>
function Qs2Dict(qs) {
var pairs = qs.split('&');
var dict = {};
pairs.forEach(function (pair) {
var kv = pair.split('=');
dict[kv[0]] = decodeURIComponent(kv[1].replace(/\+/g, "%20"));
});
return dict;
}
// Add row
$("#add-row").click(function () {
$('#pa tbody>tr:last').clone(true).insertAfter('#pa tbody>tr:last');
$('#pa tbody>tr:last #Description').val('');
$('#pa tbody>tr:last #Expected').val('');
return false;
});
$('#modal').click(function (e) {
e.preventDefault();
var url = $(this).data('url');
var data = $('form').serialize();
var dict = Qs2Dict(data);
$.ajax({
type: "POST",
url: url,
data: {
"Description": dict.Description,
"EffectiveDate": dict.EffectiveDate,
"Expected": dict.Expected,
},
success: function (result) {},
});
});
Change their name attribute, since it defines/enumerates the fields to save.
If they are equal, which they are if you clone, only the last one is taken.
Or use arrays i.e. name="Expected[]"
EDIT: more specifically: I assume they get "lost" due to above reason during $('form').serialize();

Categories

Resources