How to pass a list of objects from view - javascript

So I'm dynamically creating sections for my objects, where the entered values would be passed to the controller, but I'm having trouble with indexing. Sometimes it works and I think the problem is with my jQuery code, where some some functions are asynchronous and the indexing gets skipped.
The form submit should return a list of KPIs with KPI value, Name and employeeGID. In this example it should return a List of 4 elements, but it returns only one, because it skips 1 and 2 and goes straight to 3
In View HTML code I just have this div to indicate the place to append sections:
<div id="criteriaSections">
</div>
Scripts:
var kpiCount = 0;
function createCriteriaSection(criteria) {
var criterias = #Html.Raw(Json.Serialize(Model.Criterias));
for (var i = 0; i < criterias.length; i++)
{
if (criterias[i].id == criteria.value)
{
var critID = criteria.value;
if (criterias[i].isIndividual)
{
var section =
`<div class="settings">
<fieldset>
<legend>${criteria.text}</legend>
<table id="assignIndividualTable">
<thead>
<tr>
<th style="width:25%; text-align:center">
<label>Employee</label>
</th>
<th style="width: 65%; text-align: center">
<label>KPI Name</label>
</th>
<th style="width: 10%; text-align: center">
<label>Value</label>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</fieldset>
</div>`;
$("#criteriaSections").append(section);
showIndividualCiteriaEmployees(critID);
}
else
{
var section =
`<div class="settings">
<fieldset>
<legend>${criteria.text}</legend>
<div>
<label>KPI Name: <input type="text" name="KPI[${kpiCount}].Name" class="form-control" required></label>
<label>Value: <input type="text" name="KPI[${kpiCount}].Value" class="form-control" required></label>
<input name="KPI[${kpiCount}].CriteriaID" value="${critID}" type="hidden" />
<input name="employeeGID[${kpiCount}]" class="form-control" value="" type="hidden"/>
</div>
</fieldset>
</div>`;
$("#criteriaSections").append(section);
kpiCount++;
}
}
}
}
function showIndividualCiteriaEmployees(critID) {
var resultLength = 0;
$.post("/KPIs/GetFilteredUsers", { critID: critID }, function (result) {
resultLength = result.length;
var rows = "";
$.each(result, function (i, item) {
rows +=
`<tr>
<td style="width:20%; text-align:center">
<p>${item.text}</p>
<input name="employeeGID[${kpiCount + i}]" class="form-control" value="${item.value}" type="hidden"/>
<input name="KPI[${kpiCount}].CriteriaID" value="${critID}" type="hidden" />
</td>
<td style="width:65%; text-align:center">
<input type="text" name="KPI[${kpiCount}].Name" class="form-control" required/>
</td>
<td style="width:15%; text-align:center">
<input type="text" name="KPI[${kpiCount}].Value" class="form-control" required/>
</td>
</tr>`;
kpiCount++;
});
$("#assignIndividualTable tbody").html(rows);
});
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Date,Name,Value,ID,CriteriaID,Employee")] List<KPI> KPI, List<string> employeeGID)
{
int? id = HttpContext.Session.GetInt32("ID");
if (ModelState.IsValid)
{
for (int i = 0; i < KPI.Count; i++)
{
KPI[i].ManagersId = id.GetValueOrDefault();
KPI[i].Criteria = await _context.Criterias.FirstOrDefaultAsync(x => x.ID == KPI[i].CriteriaID);
if (KPI[i].Criteria.IsIndividual)
{
KPI[i].EmployeeId = _context.Users.First(x => employeeGID[i] == x.GID).ID;
}
}
_context.AddRange(KPI);
await _context.SaveChangesAsync();
return Create();
}
return Create();
}

Related

Reset the HTML table on change

I am working on expense management with pouchdb
The data is inserted into the database based on date
i want to reset to original table if there is no data in date onchange
Above picture is with data on particular date
if i change the date the table is not reset to original table
this picture is when changing the date the table is not resetting
only head row and one row is hard coded extra rows or dynamically created on click add row button
//add row
function addRow(no_of_rows){
for (let i = 0; i < no_of_rows; i++){
console.log(i)
var root = document.getElementById('customers').getElementsByTagName('tbody')[0];
var rows = root.getElementsByTagName('tr');
var clone = cloneEl(rows[rows.length - 1]);
cleanUpInputs(clone);
root.appendChild(clone);
function cloneEl(el) {
var clo = el.cloneNode(true);
return clo;
}
function cleanUpInputs(obj) {
for (var i = 0; n = obj.childNodes[i]; ++i) {
if (n.childNodes && n.tagName != 'INPUT') {
cleanUpInputs(n);
} else if (n.tagName == 'INPUT') {
n.value = '';
}
}
}
}
}
// getting data from pouchdb
function getAccounts(){
var getdate = document.getElementById('Expdate').value;
var table = document.getElementById('customers');
db.get(getdate, function(err, doc) {
if (err) {
//want to handle the table reset here
} else {
console.log(doc);
addRow(doc['DailyAccount'].length -1);
for (let i = 0; i < doc['DailyAccount'].length; i++){
// console.log(i);
table.rows[i+1].cells[0].firstChild.value = doc.DailyAccount[i]['Description'];
table.rows[i+1].cells[1].firstChild.value = doc.DailyAccount[i]['Investment'];
table.rows[i+1].cells[2].firstChild.value = doc.DailyAccount[i]['Expenses'];
}
document.getElementById("investtotal").value = doc.TotalInvestment;
document.getElementById("exptotal").value = doc.TotalExpenses;
}
});
}
<input type="date" name="Date" id="Expdate" onchange="getAccounts()" >
<button onclick="addRow(1)"><i class="fa fa-plus" aria-hidden="true"></i>Add Row</button>
<button onclick="DeleteRow()"><i class="fa fa-minus" aria-hidden="true"></i>Delete Row</button>
<table id="customers">
<tbody id="mytbody">
<tr>
<th>Descritption</th>
<th>Investment</th>
<th>Expenses</th>
</tr>
<tr>
<td><input type="text" name="yourname" /> </td>
<td onchange="getinvest()"><input type="number" name="yourname" /></td>
<td onchange="getexpense()"><input type="number" name="yourname" /></td>
</tr>
</tbody>
</table>
<label for="fname">Investment Total : </label>
<input type="number" name="Investtotal" id="investtotal">
<label for="fname">Expense Total : </label>
<input type="number" name="Exptotal" id="exptotal">
<input type="button" id="save" value ="save" name="save" onclick="day()">
structure of pouchdb doc
var Accountdoc = {
_id: getdate,
TotalInvestment:Totalinvest,
TotalExpenses: Totalexp,
DailyAccount: Accounts,// accounts is array of object
};

hide div if value is blank (javascript)

I am working on a phonebook. In html I have a div #containerAgenda which won't show if there are no added contacts. However, I created the function to delete a row or multiple rows. So if I add and then delete all contacts, I want the div to hide. I am not sure how to set the value to blank or empty so that I can apply the rule .classList.remove in the deleteRow function(I added the way I tried to define the input value as empty). Would you give me any hints? Below is my code:
P.S. I am quite a beginner so I appreciate non-complicated solutions :)
<script>
var persoane =[];
function deseneazaTabel(){
str = "";
for (var i = 0; i < persoane.length; i++){
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML=str;
}
var pers = {};
function adaugaContact(form,event){
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i=0; i<inputs.length; i++){
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow (idx){
persoane.splice(idx,1);
if(document.querySelectorAll("input[name]").value === ""){
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
</script>
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for ="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
What you need is if
(persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
inside deseneazaTabel function
I also added deleteAll functionality which was missing from your question please check demo
var persoane = [];
function deseneazaTabel() {
if (persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
str = "";
for (var i = 0; i < persoane.length; i++) {
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML = str;
}
function DeleteALL() {
persoane = [];
deseneazaTabel();
}
var pers = {};
function adaugaContact(form, event) {
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i = 0; i < inputs.length; i++) {
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow(idx) {
persoane.splice(idx, 1);
if (document.querySelectorAll("input[name]").value === "") {
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<input type="submit" class="btn" onClick="DeleteALL()" value="Delete ALL">
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
This can help you
function checkIfNoContact() {
if(document.querySelectorAll("tr").length <= 0 ) {
document.querySelector("#containerAgenda").classList.add("hidden");
} else {
document.querySelector("#containerAgenda").classList.remove("hidden");
}
}
You can Use jQuery
It will check if there wasn't any <tr> in <tbody>, then hides div#containerAgenda
I hope it works for you.
if ( $("#containerAgenda tbody").children().length == 0 ) {
$("#containerAgenda").hide();
}

How to prevent insert a duplicate record in Angularjs

I am loading all records from a SQL db table using Angular and web API, what I am trying to do is to prevent the user from inserting a new record in Angular in case some of the data is duplicated with other records returned data, before going to the API.
How to raise an alert to notify and tension the user when press save that there are some fields are already exist like "code", "L_Desk", "A_Desc "with the loaded data from the table.
HTML:
<body ng-app="ContractT" ng-controller="crudController">
<br /><br />
<input type="checkbox" ng-model="Hide" />Hide <input type="button" value="Clear" ng-click="resetform()" />
<input type="submit" value="Save" ng-click="save()"/> <input type="button" value="Delete" ng-click="delete(selectedMember.sys_key)" />
<fieldset>
<legend>Contract Type</legend>
<table>
<tr>
<td>Code</td>
<td><input type="text" size="10" pattern="^[a-zA-Z0-9]+$" title="Alphnumeric" required autofocus ng-model="selectedMember.Code.Staff_Type_Code">
<input type="text" size="10" hidden ng-model="selectedMember.sys_key" /> </td>
</tr>
<tr>
<td>Latin Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Latin.L_Desc"></td>
</tr>
<tr>
<td>Local Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Local.A_Desc"></td>
</tr>
<tr>
<td>No. Of Houres Per Day</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Hours_Day"></td>
</tr>
<tr>
<td>No. Of Days Per Week(s)</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Days_Week"></td>
</tr>
<tr>
<td>End Of Contract By</td>
<td>
<select ng-model="selectedContract">
<option>Age</option>
<option>Number Of Years in Service</option>
</select>
</td>
</tr>
<tr>
<td>Number</td>
<td>
<input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Num_EndWork">
<select ng-model="selectedNumber">
<option >Months</option>
<option>Years</option>
</select>
</td>
</tr>
</table>
</fieldset>
<br />
<table border="1" ng-hide="Hide">
<thead>
<tr>
<!--<th>syskey</th>-->
<th>Code</th>
<th>Latin Description</th>
<th>Local Description</th>
<th>Hours_Day</th>
<th>Days_Week</th>
<th>Num_EndWork</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in Contracts | filter:selectedMember.Code | filter:selectedMember.Latin | filter:selectedMember.Local ">
<td style="display:none;">{{c.sys_key}}</td>
<td>{{c.Staff_Type_Code}}</td>
<td>{{c.L_Desc}}</td>
<td>{{c.A_Desc}}</td>
<td>{{c.Hours_Day}}</td>
<td>{{c.Days_Week}}</td>
<td>{{c.Num_EndWork}}</td>
</tr>
</tbody>
</table>
</form>
Controller :
contractT.controller('crudController', function ($scope, crudService)
{
loadrecords();
function loadrecords()
{
crudService.getContracts().then(function (response) {
$scope.Contracts = (response.data);
$scope.selectedMember = {};
console.log($scope.Contracts);
});
}
$scope.save = function () {
debugger;
if ($scope.selectedContract == 'Age' && $scope.selectedNumber == 'Months') {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 1,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else if ($scope.selectedContract == 'Age' && $scope.selectedNumber == 'Years')
{
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 2,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else if ($scope.selectedContract == 'Number Of Years in Service' && $scope.selectedNumber == 'Months') {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 3,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 4,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
if (!$scope.selectedMember.sys_key) {
var promisePost = crudService.post(Contract);
promisePost.then(function (pl) {
loadRecords();
$scope.selectedmember = {};
}, function (err) {
console.log("Err" + err);
});
}
else
{
var promisePost = crudService.put(Contract);
promisePost.then(function (pl) {
loadRecords();
$scope.selectedmember = {};
}, function (err) {
console.log("Err" + err);
});
}
}
$scope.resetform = function () {
$scope.selectedMember = {};
//$scope.selectedMember = {};
//$scope.Local = {};
//$scope.Nhd = null;
//$scope.Ndw = null;
//$scope.Num = null;
}
$scope.selectedMember = { Code: "",sys_key:"", Latin:"" , Local:"", Hours_Day :"", Days_Week:"", Num_EndWork:"" }
$scope.showInEdit = function (member)
{
$scope.selectedMember = member;
//$scope.selectedMember.Code = member;
//$scope.selectedMember.Latin = member;
//$scope.selectedMember.Local = member;
//$scope.selectedMember.Hours_Day = member;
//$scope.selectedMember.Days_Week = member;
//$scope.selectedMember.Num_EndWork = member;
}
You can use filter here inorder to check for duplicates
var filtered= $filter('filter')($scope.contracts, function(value){
return value.Staff_Type_Code === Contract.Staff_Type_Code ;
});
if(filtered.length > 0){
console.log("duplicate exists");
}

ng-repeat is not updating when array is pushed inside scope

i have a web method which is returning json data in every call i am pushing this result into a $scope variable , but inside ng-repeat it is not binding this result . whats wrong with my code . please suggest.
here is my code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetLocationStockEntries(int LocationId, int ProductId)
{
var jsonText = (dynamic)null;
try
{
if (LocationId > 0)
{
Int64 BusinessUnitId = 0;
using (var db = new repute.Data.ReputEntities())
{
var temp = db.Inventories.Where(p => p.InventoryID == LocationId).FirstOrDefault();
BusinessUnitId = temp == null ? 0 : Convert.ToInt64(temp.BusinessUnitID);
var StockData = db.usp_mvc_InventoryItems_GetAllEntriesByLocation(LocationId, ProductId, BusinessUnitId).Where(x => x.ProjectedQuantityOnHand > 0).ToList();
jsonText = JsonConvert.SerializeObject(new { data = StockData });
}
}
}
catch (Exception ex)
{
}
return jsonText;
}
js :function which is calling this web method evertime and pushing those result into $scope variable
function GetStockEntries(loid, pid)
{
return $http.post(serviceURL + "/GetLocationStockEntries", {LocationId: loid, ProductId: pid }).then(
function success(data, status, headers, config) {
var obj = JSON.parse(data.data.d);
debugger
//$scope.result = obj.data;
$scope.result = obj;
angular.forEach($scope.result, function (key) {
$scope.StockList.push(key);
})
},
function error(data, status, headers, config) {
return data;
});
}
Html:
<table cellpadding="5" cellspacing="0" data-ng-repeat="sTockProduct in ProductList" data-ng-cloak>
<tr>
<td>{{sTockProduct.Name}}
<i class="fa fa-expand" aria-hidden="true" style="color: #000000; text-align: right; margin:5px 0px 0px 10px;" data-ng-click="StockListing(sTockProduct);"></i></td>
</tr>
<tr>
<td>
<table cellpadding="5" cellspacing="0" data-ng-repeat="stockItem in StockList track by $index" data-ng-show = "IsVisible" data-ng-cloak width="100%">
<tr style="border-bottom: 1px solid #ddd; padding-bottom: 5px; margin-bottom: 5px; float: left;">
<td>
<input type="radio" name="groupName" data-ng-value="true" data-ng-model="stockItem.selected[$index]" data-ng-click="onTaskSelect(stockItem,sTockProduct)" />
</td>
<td>
<input type="text" data-ng-model="stockItem.UserInventoryItemID" disabled="" readonly="" style="border: none; background-color: white;">
</td>
<td>
<input type="text" data-ng-model="stockItem.LotNumber" disabled="" readonly="">
</td>
<td>
<!--<input type="text" data-ng-model="stockItem.QuantityOnHand" disabled="" readonly="">-->
<span>{{stockItem.QuantityOnHand}}</span>
<span>{{stockItem.UnitName}}</span>
</td>
<td>
<input type="text" data-ng-model="stockItem.EnteredQuantity" >
</td>
<td>
<input type="text" data-ng-model="stockItem.Description" disabled="" readonly="">
</td>
</tr>
</table>
</td>
</tr>
</table>
Here is the result of json
i guess the problem is with you ng-repeat.try some thing like, do check a condition there if some thing similar in both item. in your inner table do
data-ng-if="stockItem.ProductID== sTockProduct.ProductID"
it should be like:
<table cellpadding="5" cellspacing="0" data-ng-repeat="stockItem in StockList track by $index" data-ng-if="stockItem.ProductID == sTockProduct.ProductID" data-ng-cloak width="100%">
and just a slight modification inside your success:
replace :
$scope.result = obj;
to:
$scope.result = obj.data;

How to add Edit and delete button in each row using javascript/jquery

I want to add edit and delete button in each row and want to edit and delete row using javascript. How should I do this. Please check the below jsfiddle.
First Name:<br>
<input type="text" id="fName" /><br>
Last Name: <br>
<input type="text" id="lName" /><br>
Gender: <br>
<input type="text" id="gender" /><br>
Age: <br>
<input type="text" id ="age" /> <br>
<input type="button" id ="display" value="Display" /><br>
<table id= "table" border="1">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
</tr>
</table>
javascript
(function setup() {
"use strict";
var fNameElem = document.getElementById("fName");
var lNameElem = document.getElementById("lName");
var genderElem = document.getElementById("gender");
var ageElem = document.getElementById("age");
var tableElem = document.getElementById("table");
document.getElementById("display").addEventListener("click", function () {
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(lNameElem.value + ", " + fNameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(genderElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
fNameElem.value = "";
lNameElem.value = "";
ageElem.value = "";
tableElem.value = "";
});
})();
http://jsfiddle.net/xnWSV/
Ended up using jQuery, if you click edit the fields get repopulated and then you click 'Display' again to solve the problem. This is a very simple implementation of this, but I would recommended using Angular or some kind of templating libary if you were going to expand on this.
http://jsbin.com/jevejetofo/edit?html,js,console,output
JavaScript:
(function setup() {
var selectedRow = null;
var keys = ["fName","lName","gender","age"];
function resetValues(fName,lName,gender,age){
forEachInput(function(key){
$("#"+key).val('');
});
}
function forEachInput(callback){
for(var i = 0; i < keys.length; i++) {
callback(keys[i]);
}
}
function createRow(){
var row = $(".tr_clone").clone()
var newRow = row.appendTo("table").removeClass("tr_clone").fadeIn(1000);
forEachInput(function(key){
newRow.find("."+key).text($("#"+key).val());
});
resetValues();
selectedRow = null;
}
function applyValues(row){
forEachInput(function(key){
row.find("."+key).text($("#"+key).val());
});
}
function editRow(row){
forEachInput(function(key){
$("#"+key).val(row.find("."+key).text());
});
selectedRow = row;
}
$("#display").on("click", function () {
if(selectedRow === null){
createRow();
resetValues();
} else {
applyValues(selectedRow);
resetValues();
selectedRow = null;
}
});
$("table").delegate("button").on("click",function(e){
e.preventDefault();
if($(e.target).hasClass('edit')){
editRow($(e.target).parent("td").parent("tr"));
} else {
$(e.target).parent("td").parent("tr").fadeOut(1000).remove();
}
});
})();
HTML
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>First Name:<br>
<input type="text" id="fName" /><br>
Last Name: <br>
<input type="text" id="lName" /><br>
Gender: <br>
<input type="text" id="gender" /><br>
Age: <br>
<input type="text" id ="age" /> <br>
<input type="button" id="display" value="Display" /><br>
<table id= "table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Age</th>
</tr>
<tr class="tr_clone" style="display:none;">
<td class="fName"></td>
<td class="lName"><input type="text" autofocus placeholder="location" name="location" ></td>
<td class="gender"><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
<td class="age"><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
<td class="buttons"><button class="delete">Delete</button> | <button class="edit">Edit</button></td>
</tr>
</table>

Categories