Add/remove input boxes to the table row in Angular dynamically - javascript

Somehow I can't get my head around this in angular- I have a Table and want to add the row on-click, but this row should have empty input boxes and a button to remove itself.
<tbody>
<tr>
<th>Test 1</th>
<th>200</th>
<th>Add new row</th>
</tr>
//I want to Add this part dynamically everytime when I click on Add new row
<tr>
<td>
<input type="text" placeholder="Please Enter the Address">
</td>
<td>
<input type="text" placeholder="Number of Quantity">
</td>
//On Delete it should delete just that particular row
<td>Delete</td>
</tr>
</tbody>
I have created plunker http://plnkr.co/edit/DDj5Z99tw1QuN8xlxZ7V?p=preview just for showing what I am trying to achieve. If anyone would be able to give a hint or link me to tutorial would be great!

Please have look at this plunker.
http://plnkr.co/edit/ogvezWz6WDwDhCnm2bDU
Idea is to use a row at the end whose visibility can be controlled. And using ngRepeat you can iteratively display your added product items.
<tr ng-repeat="row in rows">
<td>
{{row.product}}
</td>
<td>
{{row.quantity}}
</td>
<td>
<button ng-click="deleteRow($index)">Delete</button>
<button ng-click="addNewRow()">New</button>
</td>
</tr>
<tr ng-show="addrow">
<td>
<input type="text" placeholder="Please Enter the Address" ng-model="product"/>
</td>
<td>
<input type="text" placeholder="Number of Quantity" ng-model="quantity"/>
</td>
<td><button ng-click="save()">Save</button> <button ng-click="delete()">Delete</button></td>
</tr>
And the Controller code
angular.module('AddRow', [])
.controller('MainCtrl', [
'$scope', function($scope){
$scope.rows = [ { "product": "Test 1", "quantity": "200"}];
$scope.addrow = false;
$scope.addNewRow = function(){
$scope.addrow = true;
};
$scope.deleteRow = function(index){
//delete item from array
$scope.rows.splice(index,1);
};
$scope.save = function(){
//add item to array
$scope.rows.push({"product": $scope.product, "quantity": $scope.quantity});
//reset text input values
$scope.product = "";
$scope.quantity = "";
//hide the add new row
$scope.addrow = false;
};
$scope.delete = function(){
$scope.addrow = false;
};
}]);

Related

Can't print the Array in view using ng-repeat in angular JS

I have designed the dynamic table with the various type of the input field.We can add and delete the row as per the requirement.
Here is my HTML view code:
<body>
<div ng-app="appTable">
<div ng-controller="Allocation">
<button ng-click="add()"> Add </button>
<button ng-click="remove()">remove</button>
<table>
<th>
<td>Date</td>
<td>Project</td>
<td>Release</td>
<td>Feature</td>
<td>Module name</td>
<td>Hours spent</td>
<td>Comment</td>
</th>
<tr ng-repeat="data in dataList">
<td><input type="checkbox" ng-model="data.isDelete"/></td>
<td>
<input type="text"
datepicker
ng-model="data.date" />
</td>
<td><input type="text" ng-model="data.dept"/></td>
<td>
<select ng-model="data.release" ng-options="x for x in range">
</select>
</td>
<td>
<select ng-model="data.feature" ng-options="x for x in feature">
</select>
</td>
<td>
<input type = "text" ng-model = "data.modulename">
</td>
<td>
<select ng-model="data.hours" ng-options="x for x in hours">
</select>
</td>
<td>
<input type = "text" ng-model = "data.comment">
</td>
</tr>
</table>
<button ng-click="Submit()">Submit</button>
<tr ng-repeat="data in dataList">
<p>{{data.date}}</p>
<p>{{test}}</p>
</tr>
</div>
</div>
</body>
Here my angularJS script:
<script>
var app = angular.module("appTable", []);
app.controller("Allocation", function($scope) {
$scope.hours = ["1", "2", "3"];
$scope.range = ["1", "2", "3"];
$scope.feature = ["UT", "FSDS", "Coding/Devlopment", "QA"];
$scope.dataList = [{
date: '17/07/2016',
dept: 'OneCell',
release: '1',
feature: "UT",
modulename: "Redundancy",
hours: "1",
comment: "Add extra information"
}];
$scope.add = function() {
var data = {};
var size = $scope.dataList.length - 1;
data.date = $scope.dataList[size].date;
data.dept = $scope.dataList[size].dept;
data.release = $scope.dataList[size].release;
data.feature = $scope.dataList[size].feature;
data.modulename = $scope.dataList[size].modulename;
data.hours = $scope.dataList[size].hours;
data.comment = $scope.dataList[size].comment;
$scope.dataList.push(data);
};
$scope.Submit = function() {
$scope.test = "Submit is pressed...";
};
$scope.remove = function() {
var newDataList = [];
angular.forEach($scope.dataList, function(v) {
if (!v.isDelete) {
newDataList.push(v);
}
});
$scope.dataList = newDataList;
};
});
app.directive("datepicker", function () {
function link(scope, element, attrs, controller) {
// CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
element.datepicker({
onSelect: function (dt) {
scope.$apply(function () {
// UPDATE THE VIEW VALUE WITH THE SELECTED DATE.
controller.$setViewValue(dt);
});
},
dateFormat: "dd/mm/yy" // SET THE FORMAT.
});
}
return {
require: 'ngModel',
link: link
};
});
</script>
I have taken the dataList array(list) to store the rows the of table.Every time when row will be added or deleted then respective element in the dataList array will be added and delete.
I have put the "submit" button in my view.When this button will be pressed then all the dataList element will be printed as shown here,
<button ng-click="Submit()">Submit</button>
<tr ng-repeat="data in dataList">
<p>{{data.date}}</p>
<p>{{test}}</p>
</tr>
But some how the dataList elements are not printed.However I am able to print the value of the test string.Please help.
Here you are using plain <tr> element for ng-repeat, this will not work, as it require proper structure of table.
E.g.:
<table>
<tr ng-repeat="data in dataList">
<td>
<p>{{data.date}}</p>
</td>
</tr>
</table>
P.S. : Your submit button is doing nothing. Just printing one statement. Above code of ng-repeat will work on each add and delete statement. i.e. it will print data simultaneously.

Define and get values from angularJS table

Here is my angularjs code to get values in a table and save. If I put some data in table and save, Its working fine but if I click save without entering any data in table it shows error as
TypeError: $scope.item is undefined
Here is my code and please help me. I am a newbie in angularJS
<div ng-app="Myapp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-messages.js"></script>
<script>
var Myapp = angular.module('Myapp', ["ngRoute"]);
</script>
<div ng-controller="orderFormController">
<table id="item_table">
<thead>
<tr class="headings">
<th class="column-title">Item </th>
<th class="column-title">Rate</th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="item" ng-model='item[0]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[0]'>
</td>
</tr>
<tr>
<td>
<input type="text" name="item" ng-model='item[1]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[1]'>
</td>
</tr>
</tbody>
</table>
<button type="button" ng-click='saveorder()' >SAVE ORDER</button>
</div>
<script>
Myapp.controller('orderFormController', ['$scope', '$http', function ($scope, $http) {
var data = {};
data['item'] = [];
$scope.saveorder = function () {
var rowCount = 3;
for (i = 1; i < rowCount; i++) {
data['item'][i] = {'item': $scope.item[i], 'rate': $scope.rate[i]}
}
alert(data);
}
}]);
</script>
$scope.item is not defined anywhere except for in that for loop, if there are no values in the table, then $scope.item will remain undefined. You could simply declare it prior to the for loop, and set some init values, which could be done in the controller, or by using the ng-init directive.
Also, I would recommend using the ng-repeat directive for your table rows, it will create a template per item from a collection, which makes your code easier to manage. Here's the documentation: ngRepeat
modify your html to only include this not 2 rows of input
<td>
<input type="text" name="item" ng-model='item'>
</td>
<td>
<input type="text" name="rate" ng-model='rate'>
</td>
and modify your saveOrder
$scope.saveorder = function () {
if (!($scope.item.length && $scope.rate.length)){
alert('can\'t be empty');
return;
}
data['item'].push({'item': $scope.item, 'rate': $scope.rate});
$scope.item = "";
$scope.rate = "";
console.log(data['item'][data['item'].length - 1]);
alert(data);
}

Iterating through table and get the value of a button in each tablerow jQuery

I have buttons in a table which are created dynamically. I want to iterate through a table, get the tablerows which contain a checked checkbox and get the value of a button inside the tablerow. I want to push the values in an array after. The buttons don't have a unique ID so I cannot get their values by id.
I tried to get the values through giving the buttons a class and itering works fine but the array is filled with empty entries.
$("#bt_multiple_deletion").off().on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).find(".filefolder-button").text());
});
})
I really don't know what Im doing wrong. I tried to get the values with .text(), .val() etc.
My table row looks like this:
<tr class="select">
<td>
<span class="countEntries"><input id="lv_fifo_ctrl7_cb_delete_file" type="checkbox" name="lv_fifo$ctrl7$cb_delete_file" /></span>
</td>
<td>
<img src="images/icons/013_document_02_rgb.png" alt="document" />
</td>
<td class="name">//the button i want to get the value from
<input type="submit" name="lv_fifo$ctrl7$bt_file" value="013_document_png.zip" id="lv_fifo_ctrl7_bt_file" class="filefolder-button download file del" style="vertical-align: central" />
</td>
<td>
<span id="lv_fifo_ctrl7_lb_length">33.14 KB</span>
</td>
<td>
<span id="lv_fifo_ctrl7_lb_CreationTime">21.10.2014 07:34:46</span>
</td>
<td></td>
<td>
<input type="submit" name="lv_fifo$ctrl7$bt_del_file" value="delete" id="lv_fifo_ctrl7_bt_del_file" class="delete-button delete-file" />
</td>
</tr>
The problem is rows is the input elements not the tr elements so in the loop you need to find the tr which contains the input then find the target element inside it
$("#bt_multiple_deletion").off().on("click", function () {
var checked = $(".select").find("input[type=checkbox]:checked");
var files = checked.map(function () {
return $(this).closest('tr').find(".filefolder-button").val();
}).get();
})
Another option is
$("#bt_multiple_deletion").off().on("click", function () {
var rows = $(".select").find("tr").has('input[type=checkbox]:checked');
//var rows = $(".select").find('input[type=checkbox]:checked').closest('tr');
var files = rows.map(function () {
return $(this).find(".filefolder-button").val();
}).get();
})
#Timo Jokinen Do you need this
$("#bt_multiple_deletion").on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).parents("tr").find("td.filefolder-button").text());
});
console.log(files);
})
<table class="select">
<tr>
<td class="filefolder-button">test1</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test2</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test3</td>
<td><input type="checkbox" /></td>
</tr>
</table>
<button id="bt_multiple_deletion">delete</button>
Checkout example link here

How can I append text with table tr using knockout

I have got a assignment to implement knockout js to my application. I have a table like
<table>
<tr>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
<th></th>
</tr>
<tr>
<td>
Iphone
</td>
<td>
SmartPhone
</td>
<td>
50000
</td>
</tr>
</table>
There are three textbox for creation of this field.
<div id="create">
<input data-bind="value: Name" id="name"/>
<input data-bind="value: Category" id="category"/>
<input data-bind="value: Prize" id="prize"/>
</div>
When I am typing on this textboxes i want to show this on the table as a new tr.. How can I do this? DEMO
Reference Link
What you want to do is define a viewmodel that contains the data for an individual item, and another viewmodel that contains the rest of the interactions (list of items, how to add new ones, etc).
var Item = function (Name, Category, Price) {
var self = this;
self.Name = ko.observable(Name);
self.Category = ko.observable(Category);
self.Price = ko.observable(Price);
}
var ViewModel = function () {
var self = this;
self.ItemToAdd = ko.observable(new Item());
self.Items = ko.observableArray([]);
self.addItem = function (item) {
self.Items.push(item);
self.ItemToAdd(new Item());
}
};
var vm = new ViewModel();
vm.addItem(new Item('Iphone', 'SmartPhone', 50000));
ko.applyBindings(vm);
In your html, your table body will look like this:
<tbody data-bind="foreach: Items">
<tr>
<td data-bind="text: Name"/>
<td data-bind="text: Category"/>
<td data-bind="text: Price"/>
</tr>
</tbody>
what this does is loops through each item in the Itemlist and creates a <tr> for each one and binds the values of the Item object in the observableArray to the <td> elements.
to add new items to the table in your markup:
<div data-bind="with: ItemToAdd">
<input data-bind="value: Name" id="name"/>
<input data-bind="value: Category" id="category"/>
<input data-bind="value: Price" id="price"/>
<button data-bind="click: $parent.addItem">Add</button>
</div>
this sets the context of the div element to a new Item object, and when you click the Add button, it calls the parent context's (ViewModel) addItem function, and automatically passes the context item for the div element (ItemToAdd). Then its just a matter of pushing it on to the observableArray and the table will update with the new item.
Updated Fiddle: http://jsfiddle.net/BJQgw/4/
if this was a for-real application, you would perform some sort of validation prior to adding the item to the list (preferably using knockout-validation)

Deleting a specific row in a table

I'm trying to delete a specific row from a table using javascript. The way I'm trying to do it now, is by retrieving the ID of the current row by clicking a button (the delete button) and then deleting the row. The problem is that I'm not retrieving the current row ID in the table. If someone could help me retrieve the the ID of the current row when the user clicks the delete button, I think I can solve the rest myself. Thanks
/*The Javascript*/
function delete_row() {
alert('id goes here');
//getElementById('row').innerHTML ='hello';
//id.deleteRow();
//var table = document.getElementByTagName('items_table');
//var row = table.rows[index];
//document.getElementByTagName('items_table').deleteRow(0);
}
/*The HTML of the Table*/
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
/* Five rows in this table... */
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
</table>
You could just ascend the tree until you find a row:
function delete_row(btn) {
var tr = btn;
while(tr && tr.nodeName != "TR") tr = tr.parentNode;
if( !tr) throw new Error("Failed to find the row, was the function called correctly?");
tr.parentNode.removeChild(tr); // delete it
}
And:
<button onClick="delete_row(this);">X</button>
The this is important, as it provides a reference to the button that was clicked, so we can find the row it is in.
Check this code. It has been verified and will do your job perfectly. :)
<script>
function delete_row(me) {
alert(me.parentNode.parentNode.id);
}
</script>
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
</table>
Can't you just change <button onclick="delete_row();">X</button> to <button onclick="delete_row('row_5');">X</button>, in each row, respectively?
Your handler would look like:
function delete_row(theID) {
alert(theID);
}

Categories

Resources