Dynamically create table and rows - javascript

How can I create a table dynamically and then add rows to the table? I have been able to create the table with one row with form fields, but how I can add additional rows? Any example on how it has been implement would helpful. I did in angular 2.
screenshot
$scope.newItem = function($event, valI) {
$scope['questionelemnt'].push({
id: counter,
title: '',
desc: '',
Qty: '',
price: '',
total: ''
});
}
Any help in angular or jquery.

Directive ng-app & ng-controller code
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="helloApp">
<head>
<title>Hello AngularJS - Add Table Row Dynamically</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="assets/js/controllers.js"></script>
</head>
<!-- Controller name goes here -->
<body ng-controller="CompanyCtrl">
...
</body>
</html>
Controller CompanyCtrl code in controller.js
<script>
var helloApp = angular.module("helloApp", []);
helloApp.controller("CompanyCtrl", function($scope) {
$scope.questions = [];
$scope.addRow = function(){
$scope.questions.push({ 'title':$scope.title, 'desc': $scope.desc, 'Qty':$scope.Qty,'price':$scope.price,'total':$scope.total });
$scope.title='';
$scope.desc='';
$scope.Qty='';
$scope.price='';
$scope.total='';
};
)};
</script>
Directive ng-repeat code
<table class="table">
<tr>
<th>title
</th>
<th>desc
</th>
<th> Qty
</th>
<th>price
</th>
<th>total
</th>
</tr>
<tr ng-repeat="question in questions">
<td>{ {question.title}}
</td>
<td>{ {question.desc}}
</td>
<td>{ {question.Qty}}
</td>
<td>{ {question.price}}
</td>
<td>{ {question.total}}
</td>
</tr>
</table>
**Directive ng-submit code**
<form class="form-horizontal" role="form" ng-submit="addRow()">
<div class="form-group">
<label class="col-md-2 control-label">title</label>
<div class="col-md-4">
<input type="text" class="form-control" name="title"
ng-model="title" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">desc</label>
<div class="col-md-4">
<input type="text" class="form-control" name="desc"
ng-model="desc" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Qty</label>
<div class="col-md-4">
<input type="text" class="form-control" name="Qty"
ng-model="Qty" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">price</label>
<div class="col-md-4">
<input type="text" class="form-control" name="price"
ng-model="price" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">total</label>
<div class="col-md-4">
<input type="text" class="form-control" name="total"
ng-model="total" />
</div>
</div>
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Submit" class="btn btn-primary"/>
</div>
</div>
Happy Coding ,Hope it will help you

Related

PHP file_get_contents fetch dynamic html td values generated using JavaScript

I am developing a webpage where a user can add or delete rows to an HTML table.
The process is:
They will fill up the input widget on the webpage.
After filling up the description, unit, quantity, unit price, and pressing the add button; the data will be shown in the table. They will be able to add as many items as they want, and they will also be able to delete items whenever they want. Everything works fine up until here.
Once the user is done filling up the necessary forms, as well as adding the items they need, they will press the 'Save' button.
After pressing the 'Save button', I will fetch the values in the input field and the rows in the HTML table using POST method.
I will save the data in the database.
The dilemma is I can't fetch the rows in the table.
I researched some ways to fetch data from HTML tables using PHP, and I found out about file_get_contents function. It works perfectly fine with pre-defined tables, but not in dynamic tables.
I noticed that file_get_contents function fetches the HTML contents in the webpage, which is empty because the table will be filled when the user is using it, not when the page is created.
Now I feel like I hit the wall, and I do not have an idea for alternatives to achieve what I want.
I hope you can give me some advice. Thank you.
My webpage code:
<?php
session_start();
if (!isset($_SESSION['loggedIn']) ) {
header('Location: index.php');
}
if (isset($_POST['jo_save'])) {
$pageContents = file_get_contents('job_order_form.php');
$dom = new DOMDocument();
$tableData = $dom->getElementsByTagName('td');
$ctr1 = 0;
$ctr2 = 0;
foreach ($tableData as $node) {
$contents[$j][] = trim($node->textCotent);
$i++;
$j = $j % 5 == 0? $j++ : $j;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<?php require('navbar.php');?>
<div class="container">
<h3 class="display-4">Job Order</h3>
<form action="<?php echo $path_parts['basename'];?>" method="POST" id="jo_information">
<div class="form-row">
<div class="form-group col-md-8">
<label for="jo_clientName">Client Name </label>
<input class="form-control" id="jo_clientName" name="jo_clientName" />
</div>
<div class="form-group col-md-4">
<label for="jo_date">Date(mm/dd/yyyy) </label>
<input class="form-control" id="jo_date" name="jo_date" value="<?php echo date('m/d/Y');?>" readonly/>
</div>
<div class="form-group col-md-8">
<label for="jo_representative">Representative</label>
<input class="form-control" id="jo_representative" name="jo_representative" />
</div>
<div class="form-group col-md-4">
<label for="jo_tin">TIN#</label>
<input class="form-control" id="jo_tin" name="jo_tin" />
</div>
<div class="form-group col-md-12">
<label for="jo_address">Address</label>
<input class="form-control" id="jo_address" name="jo_address" />
</div>
<div class="form-group col-md-12">
<label for="jo_location">Project Location</label>
<input class="form-control" id="jo_location" name="jo_location" />
</div>
</div>
<hr />
<div class="form-row">
<div class="form-group col-sm-12 col-md-4">
<label for="jo_creator">Created By:</label>
<input class="form-control" id="jo_creator" name="jo_creator" value="<?php echo $_SESSION['employee_fName']." ".$_SESSION['employee_mName']." ".$_SESSION['employee_lName']?>" readonly />
</div>
<div class="form-group col-sm-12 col-md-4">
<label for="jo_mobilization">Mobilization</label>
<input class="form-control" id="jo_mobilization" name="jo_mobilization" />
</div>
<div class="form-group col-sm-12 col-md-4">
<label for="jo_totalPayment">Total Payment</label>
<input type="number" class="form-control" id="jo_totalPayment" name="jo_totalPayment" readonly/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<button type="submit" class="form-control btn btn-primary" id="jo_save" name="jo_save">Save</button>
</div>
<div class="form-group col-md-3">
Cancel
</div>
</div>
</form>
<form action="<?php echo $path_parts['basename'];?>" method="POST" id="jo_items">
<div class="form-row">
<div class="form-group col-md-5">
<label for="jo_description">Description</label>
<input class="form-control" id="jo_description" name="jo_description" />
</div>
<div class="form-group col-md-2 col-sm-6">
<label for="jo_unit">Unit</label>
<input class="form-control" id="jo_unit" name="jo_unit" />
</div>
<div class="form-group col-md-2 col-sm-6">
<label for="jo_quantity">Qty.</label>
<input type="number" class="form-control" id="jo_quantity" name="jo_quantity"/>
</div>
<div class="form-group col-md-2">
<label for="jo_unitPrice">Unit Price</label>
<input type="number" class="form-control" id="jo_unitPrice" name="jo_unitPrice" />
</div>
<div class="form-group col-md-1">
<label for="jo_add">&nbsp</label>
<button type="button" class="form-control btn btn-primary" id="jo_add" name="jo_add">Add</button>
</div>
</div>
<table class="table table-striped table-sm" id="jo_item_table">
<thead class="thead-dark">
<tr>
<th scope="col">Description</th>
<th scope="col">Unit</th>
<th scope="col">Quantity</th>
<th scope="col">Unit Price</th>
<th scope="col">Amount</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<hr />
</form>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#jo_add").on('click', function() {
item_amount = parseFloat($('#jo_quantity').val()*$('#jo_unitPrice').val());
new_row = "<tr> \
<td>"+$('#jo_description').val()+"</td> \
<td>"+$('#jo_unit').val()+"</td> \
<td>"+$('#jo_quantity').val()+"</td> \
<td>"+$('#jo_unitPrice').val()+"</td> \
<td>"+item_amount+"</td> \
<td><button type='button' class='btn btn-outline-danger btn-sm' onClick='deleteRow(this)'>Delete</button></td>";
jo_items_tbl = $('table tbody');
jo_items_tbl.append(new_row);
$('#jo_totalPayment').val(computeTotal);
$('#jo_description').val("");
$('#jo_unit').val("");
$('#jo_quantity').val("");
$('#jo_unitPrice').val("");
});
});
function deleteRow(cell){
var row = $(cell).parents('tr');
var rIndex = row[0].rowIndex;
document.getElementById('jo_item_table').deleteRow(rIndex);
}
function computeTotal(){
var totalAmount = 0.0;
var tbl = document.getElementById('jo_item_table');
for(var row=1, n=tbl.rows.length; row<n; row++){
totalAmount += parseFloat(tbl.rows[row].cells[4].innerHTML);
}
return totalAmount;
}
</script>
</body>
</html>
Some screenshots of the webpage:
enter image description here
enter image description here
Consider using a database (sqlite, mysql), or if you really want to use files, use CSV.
$file_name = "file.csv";
if (($handle = fopen($file_name, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
echo $data[0] . $data[1] . $data[2];
}
fclose($handle);
}
$fp = fopen($file_name, 'a');
// data to write
$infos = ["abc", "123"];
foreach ($infos as $info) {
fputcsv($fp, array($info));
}
fclose($fp)
Edit: "5: I will save the data in the database."
In that case, you can fetch the records from the database, no need to read from files.

How to show a input value in the same page in laravel using Javascript?

Im trying show de year that the user put in the input with the id 'searchBar' and show it on the lable with the 'outp' id in the table on the same laravel page with javascript.
But its just not working..
Heres my show.blade.php
<div class="row">
<div class="form-group col-2">
<form action="" method="GET" role="search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" id="seachBar" name="q" placeholder="Search year">
<button type="submit" id="btn"></button>
</span>
</div>
</form>
</div>
</div>
<div class="row">
<div class="form-group col-2">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="text-left" style="width: 5%">Data</th>
</tr>
</thead>
<tbody>
<tr scope="row">
<td class="text-left">31/01/<lable id="outp"></p></td>
</tr>
i have already connected the javascipt file with this:
<script src="{{ asset('js/showYear.js') }}" type="text/javascript"></script>
and this is my javascript file showYear.js :
var year = document.getElementById('seachBar').value;
document.getElementById('btn').onclick = function showYear(year)
{
document.getElementById('outp').innerHTML = year;
}
im new to laravel and javascript i started maybe 2 to 3 weeks ago on my intership so im kinda lost :) .
help would be great, tkx
Try with below code,
$(document).ready(function() {
$("#seachBar").keyup(function() {
$("#outp").html($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="form-group col-2">
<form action="" method="GET" role="search">
<div class="input-group">
<input type="text" class="form-control" id="seachBar" name="q" placeholder="Search year">
<button type="submit" id="btn">Submit</button>
</span>
</div>
</form>
</div>
</div>
<div class="row">
<div class="form-group col-2">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="text-left" style="width: 5%">Data</th>
</tr>
</thead>
<tbody>
<tr scope="row">
<td class="text-left" id="outp"></td>
</tr>
</tbody>
</table>

thymeleaf: Retain selected value in dropdown

I am creating a simple webpage for report generation using springboot + thymeleaf. I have 2 dropdown values one dependent on another. I have tried selecting value in dropdown and upon selection, i have onchange event that calls JavaScript to get the values for the selected dropdown. While it does that, the selected value is not retaining in the dropdown, it get reset to default option.
I tried ways suggested in forums but none are easy for me to understand.
I have provided my code snippet below, please educate me what can i do to get my value retained in the first dropdown..
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Dashboard</title>
<!-- Bootstrap core CSS -->
<link href="../static/css/bootstrap.css" rel="stylesheet" th:href="#{/css/bootstrap.css}"/>
<link href="../static/css/start-test-view.css" rel="stylesheet" th:href="#{/css/start-test-view.css}"/>
</head>
<script>
function retrieveAppName() {
if (history.pushState) {
var selectedLOB = document.getElementById('lob').value;
var _url = location.href;
var newurl = ( _url.indexOf('lob') !== -1 ) ? _url : _url+'lob?lob='+selectedLOB;
window.history.pushState({path:newurl},'',newurl);
location.reload();
}
}
</script>
<body>
<div align="center">
<div class="container">
<div class="row">
<div class="navbar-logo">
<img alt="Dashboard" th:src="#{/img/logo.svg}">
</div>
</div>
</div>
<header>
<div class="navbar-primary">
<div class="container">
<div class="row">
<span class="portal">Report Summary</span>
</div>
</div>
</div>
<div class="navbar-secondary"></div>
</header>
<div align="Left">
<div class="container main-content">
<div class="row card">
<form class="form" th:action="#{/}" th:object="${dashboardParams}" method="post">
<div class="row">
<div class="col-sm-6 text-container">
<label class="input-label">Line Of Business</label>
<select th:name="lob" class="input-field" id="lob" name="lob" onchange="retrieveAppName()">
<option value="0">--select LOB--</option>
<option value="1">ALL</option>
<option th:each="lob:${listLOB}"
th:value="${lob.line_of_business}"
th:text="${lob.line_of_business}"></option>
</select>
</div>
<div class="col-sm-6 text-container">
<label class="input-label">Application Name</label>
<select class="input-field" id="appName" name="Application Name">
<option value="0">--select Name--</option>
<option value="1">ALL</option>
<option th:each="app:${listAppName}"
th:value="${app.app_Name}"
th:text="${app.app_Name}"></option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6 text-container">
<label class="input-label">Start Date</label>
<input class="input-field" type="date" id="sDate" name="Start Date"/>
</div>
<div class="col-sm-6 text-container">
<label class="input-label">End Date</label>
<input class="input-field" type="date" id="eDate" name="End Date"/>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<button name="Generate Report" class="submit" type="submit">Generate Report</button>
</div>
</div>
</form>
</div>
</div>
</div>
<br/><br/>
<div class="table">
<table class="table table-bordered table-sm">
<thead class ="thead-light">
<tr>
<th>Application ID</th>
<th>Application Name</th>
<th>Status</th>
<th>TestCase Path</th>
<th>Environment</th>
<th>Execution Date</th>
</tr>
</thead>
<tbody>
<tr th:each="runs : ${listRuns}">
<td th:text="${runs.app_ID}">Application ID</td>
<td th:text="${runs.app_Name}">Application Name</td>
<td th:text="${runs.status}">Status</td>
<td th:text="${runs.testcasepath}">TestCase Path</td>
<td th:text="${runs.environment}">Environment</td>
<td th:text="${runs.execdate}">Execution Date</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
Controller Code:
#GetMapping("/lob")
public ModelAndView viewLOB(Model model, #RequestParam(value="lob", required=false) String lob) {
List<AppData> lobName = dao.listLOB();
List<AppData> appName = dao.listAppName(lob);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("listLOB", lobName);
modelAndView.addObject("listAppName",appName);
model.addAttribute("lastselected", lobName);
modelAndView.setViewName("dashboardParams");
return modelAndView;
}

Laravel 5 autocomplete Jquery

I have a problem with my project.
I want an autocomplete input that gets the data from a database, so the problem starts when I enter the view where the autocomplete input is. The view only gives me a white screen with an array that contains all the values ​​in my "clientes" table (the values for the autocomplete input are taken from this table).
I think the problem may be on my routes, but I do not know what to do.
Routes:
Route::get('/nuevaVenta', 'ventas#index');
Route::get('/nuevaVenta', 'ventas#autocomplete');
Controller (ventas.php):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Cliente;
use Illuminate\Support\Facades\Input;
class ventas extends Controller
{
public function index(){
return view('/nuevaVenta');
}
public function autocomplete(Request $Request){
$term = Input::get('term');
$results = array();
$queries = Cliente::where('nombre', 'LIKE', '%'.$term.'%')
->orWhere('apellido_paterno', 'LIKE', '%'.$term.'%')
->take(10)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->nombre.' '.$query->apellido_paterno.' '.$query->apellido_materno];
}
return response()->json($results);
//\Response::json($results);
}
}
View (nuevaVenta.blade.php):
#extends('master')
#section('contenido')
<script src="{{asset("js/validaciones.js")}}"></script>
<script src="{{asset("js/nuevaVenta.js")}}"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<form class="form-horizontal" action="{{url('/nuevaVenta')}}" method="GET">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<br>
<div class="form-control" style="background-color: lightblue"><label>Registro de Ventas</label></div>
<div class="col-xs-12" style="border:1px solid lightblue">
<div class="form-group">
<label class="control-label col-sm-12" style ="color: #4cae4c">Clave:0001</label>
</div>
<div class="form-group">
<label class="control-label col-sm-1" style ="font-weight: normal">Cliente:</span></label>
<div class="col-sm-10">
<input type="text" name="cliente" class="form-control solo-letras" id="cliente" style="width: 40%;" placeholder="Buscar cliente..." required>
</div>
</div>
<hr>
<div class="form-group">
<label class="control-label col-sm-1" style ="font-weight: normal">Artículo:</label>
<div class="col-sm-10">
<input type="text" name="cliente" class="form-control" style="width: 40%; display: inline;" placeholder="Buscar Artículo..." required>
<span class="glyphicon glyphicon-plus btn btn-primary"></span>
</div>
</div>
<hr>
<div class="col-xs-12">
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Descripción Artículo</th>
<th>Modelo</th>
<th>Cantidad</th>
<th>Precio</th>
<th>Importe</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
#stop
js file (ventas.js):
$(document).ready(function(){
$('#cliente').autocomplete({
autoFocus: true,
minLength:3,
dataType: "json",
source:'ventas/autocomplete',
select:function(event, ui){
alert(ui);
}
});
});
I'm using the autocomplete widget from the jquery-ui library
Your route seems duplicating, that is why, so use unique routes,
Route::get('/nuevaVenta', 'ventas#index');
Route::get('/nuevaVentaAutocomplete', 'ventas#autocomplete');

the data in model personalDeatail.add value is not updated automatically. what am i doing wrong?

I'm trying to add two column data automatically but the data in model personalDeatail.add value is not updated automatically. what am i doing wrong?? I can get the added data in the input box but same data is not updated in the personalDetail.add? please help
index.html
<!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <script src="script/angular.min.js"></script> <script src="script/script.js"></script> <script src="script/scripts.js"></script> <title>Dynamically Add-Remove Rows from Table</title>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body ng-app="myapp" ng-controller="ListController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form ng-submit="addNew()">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" /></th>
<th>Number1</th>
<th>number2</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="personalDetail in personalDetails">
<td>
<input type="checkbox" ng-model="personalDetail.selected"/></td>
<td>
<input type="text" class="form-control" ng-model="personalDetail.num1" required/></td>
<td>
<input type="text" class="form-control" ng-model="personalDetail.num2" required/></td>
<td>
<input type="text" class="form-control" value="{{parseFloat(personalDetail.num1)+parseFloat( personalDetail.num2)}}"
></td>
</tr>
</tbody>
</table>
<div class="form-group">
<input ng-hide="!personalDetails.length" type="button" class="btn btn-danger pull-right" ng-click="remove()" value="Remove">
<input type="submit" class="btn btn-primary addnew pull-right" value="Add New">
</div>
</form>
{{personalDetails}}
</div>
</div>
</div>
</div>
</div> </body> </html>
script.js
var app = angular.module("myapp", []); app.controller("ListController", ['$scope', function($scope) {
$scope.personalDetails = [
{
'num1':'',
'num2':'',
'add':''
}];
$scope.addNew = function(personalDetail){
$scope.personalDetails.push({
'num1': "",
'num2': "",
'add': ""
});
};
$scope.parseFloat = function(value)
{
return parseFloat(value);
}
$scope.remove = function(){
var newDataList=[];
$scope.selectedAll = false;
angular.forEach($scope.personalDetails, function(selected){
if(!selected.selected){
newDataList.push(selected);
}
});
$scope.personalDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.personalDetails, function(personalDetail) {
personalDetail.selected = $scope.selectedAll;
});
};
}]);
It's happening because you don't have ng-model set for the 3rd input box,
you could write a function to calculate the sum and assign the value to the $scope variable.
Demo
var app = angular.module("myapp", [])
app.controller("ListController", ['$scope', function($scope) {
$scope.personalDetails = [{
'num1': '',
'num2': '',
'add': ''
}];
$scope.calculateSum = function(val) {
val.add = parseFloat(val.num1) + parseFloat(val.num2);
}
$scope.addNew = function(personalDetail) {
$scope.personalDetails.push({
'num1': "",
'num2': "",
'add': ""
});
};
$scope.parseFloat = function(value) {
return parseFloat(value);
}
}]);
<html>
<head>
<meta charset="UTF-8">
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="script.js"></script>
<title>Dynamically Add-Remove Rows from Table</title>
<link rel='stylesheet prefetch' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
</head>
<body ng-app="myapp" ng-controller="ListController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form ng-submit="addNew()">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</th>
<th>Number1</th>
<th>number2</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="personalDetail in personalDetails">
<td>
<input type="checkbox" ng-model="personalDetail.selected" />
</td>
<td>
<input type="text" ng-keyup="calculateSum(personalDetail)" class="form-control" ng-model="personalDetail.num1" required/>
</td>
<td>
<input type="text" ng-keyup="calculateSum(personalDetail)" class="form-control" ng-model="personalDetail.num2" required/>
</td>
<td>
<input type="text" ng-model="personalDetail.add" class="form-control" >
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<input ng-hide="!personalDetails.length" type="button" class="btn btn-danger pull-right" ng-click="remove()" value="Remove">
<input type="submit" class="btn btn-primary addnew pull-right" value="Add New">
</div>
</form>
{{personalDetails}}
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Categories

Resources