Angular JS splice not working - javascript

I have my data in products.json like this:
{
"products":[
{
"name":"Antricot de vita",
"calorii":236,
"proteine":17.4,
"lipide":18.5,
"carbohidrati":0,
"fibre":0
},
{
"name":"Muschi de vita crud",
"calorii":215,
"proteine":19,
"lipide":15,
"carbohidrati":0,
"fibre":0
},
{
"name":"Albus de ou",
"calorii":52,
"proteine":10.9,
"lipide":0.2,
"carbohidrati":0.7,
"fibre":0
}
]
}
So, as you can see I have an array called products which comes with some objects each one having 6 properties.
I have a table in which every tr has 6 tds with the properties mentioned. When clicked the button on right of each tr I want that tr to be deleted.
The problem occures when I have to delete an element from the table. I have tried a splice function which seems not to work.
Please help me fix this issue. Thank you so much!
PS: The push function does work!
Below is my code:
app.js
var app = angular.module('Calorii', []);
app.factory('products', ['$http', function($http) {
return $http.get('products.json')
.success(function(data) {
return data;
})
.error(function(data) {
console.log("error");
return data;
});
}]);
app.controller('HomeController', ['$scope', 'products', function($scope, products) {
products.success(function(data) {
$scope.produse = data;
$scope.predicate = 'name';
$scope.reverse = false;
$scope.order = function(predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
$scope.removeItem = function(item) {
var index = $scope.produse.products.indexOf(item);
$scope.produse.products.splice(index, 1);
};
$scope.add = function() {
if (angular.isDefined($scope.name) && $scope.name != '' && $scope.calorii >= 0 &&
$scope.proteine >= 0 && $scope.lipide >= 0 && $scope.carbohidrati >= 0 &&
$scope.fibre >= 0) {
$scope.produse.products.push({
name: $scope.name,
calorii: $scope.calorii,
proteine: $scope.proteine,
lipide: $scope.lipide,
carbohidrati: $scope.carbohidrati,
fibre: $scope.fibre
});
$scope.name = '';
$scope.calorii = '';
$scope.proteine = '';
$scope.lipide = '';
$scope.carbohidrati = '';
$scope.fibre = '';
} else {
alert("Unul sau mai multe spatii nu a fost completat");
}
};
});
}]);
app.directive('myElement', function() {
return {
scope: {
item: '=myElement'
},
restrict: 'EA',
template: '<td class="left">{{ item.name }}</td><td>{{ item.calorii }}</td><td class=>{{ item.proteine }}</td><td class>{{ item.lipide }}</td><td class=>{{ item.carbohidrati }}</td><td class=>{{ item.fibre }}</td><td><button ng-click="removeItem(product)"><img src="images/remove.png"/></button></td>'
};
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Calorii</title>
<script src="js/shared/angular.js"></script>
<script src="js/shared/jquery-2.2.2.min.js"></script>
<link href="css/main.css" rel="stylesheet" />
</head>
<body ng-app="Calorii" ng-controller="HomeController">
<div class="main">
<div id="header">
<img src="images/kilocalorii-logo.png">
<ul id="nav">
<li id="menulink"></li>
<li id="genlink"></li>
<li id="searchspot">
<form id="searchform" class="searchform">
<input id="s" type="search" ng-model="query">
</form>
</li>
</ul>
<div id="rapidfindlabel"></div>
</div>
<div class="content">
Doresc tabelul nesortat
<table class="tabelcalorii">
<tbody>
<tr>
<th class="left">
Aliment
<span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
</th>
<th>
Calorii
<span class="sortorder" ng-show="predicate === 'calorii'" ng-class="{reverse:reverse}"></span>
</th>
<th>
Proteine
<span class="sortorder" ng-show="predicate === 'proteine'" ng-class="{reverse:reverse}"></span>
</th>
<th>
Lipide
<span class="sortorder" ng-show="predicate === 'lipide'" ng-class="{reverse:reverse}"></span>
</th>
<th>
Carbohidrati
<span class="sortorder" ng-show="predicate === 'carbohidrati'" ng-class="{reverse:reverse}"></span>
</th>
<th>
Fibre
<span class="sortorder" ng-show="predicate === 'fibre'" ng-class="{reverse:reverse}"></span>
</th>
<th>Scoate din lista</th>
</tr>
<tr ng-repeat="product in produse.products | orderBy:predicate:reverse | filter:query" my-element="product"></tr>
</tbody>
</table>
<p class="more"><strong>Nota:</strong> Toate valorile nutritive sunt calculate pentru o cantitate de 100g.</p>
<p style="margin-left:5px">Daca nu ai gasit alimentul cautat, adauga-l completand tabelul de mai jos:</p>
<table cellspacing="1" cellpadding="4" width="100%" class="add_table">
<tbody>
<tr>
<td class="add_name"><b>Aliment:</b></td>
<td class="add_value"><input type="text" ng-model="name" placeholder="Introdu numele alimentului" style="width: 215px"><br></td>
<td><span class="sugestie">exemplu: <b>Pate de porc cu verdeturi Bucegi</b></span></td>
</tr>
<tr>
<td class="add_name" valign="top"><b>Calorii:</b></td>
<td class="add_value"><input type="number" ng-model="calorii" placeholder="Introdu numarul de calorii" style="width: 215px"><br></td>
<td><span class="sugestie">completarea numarului de calorii este obligatorie</span></td>
</tr>
<tr>
<td class="add_name" valign="top"><b>Proteine:</b></td>
<td class="add_value"><input type="number" ng-model="proteine" placeholder="Introdu numarul de proteine" style="width: 215px"><br></td>
<td><span class="sugestie">completarea numarului de proteine este obligatorie</span></td>
</tr>
<tr>
<td class="add_name" valign="top"><b>Lipide:</b></td>
<td class="add_value"><input type="number" ng-model="lipide" placeholder="Introdu numarul de lipide" style="width: 215px"><br></td>
<td><span class="sugestie">completarea numarului de lipide este obligatorie</span></td>
</tr>
<tr>
<td class="add_name" valign="top"><b>Carbohidrati:</b></td>
<td class="add_value"><input type="number" ng-model="carbohidrati" placeholder="Introdu numarul de carbohidrati" style="width: 215px"><br></td>
<td><span class="sugestie">completarea numarului de carbohidrati este obligatorie</span></td>
</tr>
<tr>
<td class="add_name" valign="top"><b>Fibre:</b></td>
<td class="add_value"><input type="number" ng-model="fibre" placeholder="Introdu numarul de fibre" style="width: 215px"><br></td>
<td><span class="sugestie">completarea numarului de fibre este obligatorie</span></td>
</tr>
<button class="submit" ng-click="add()">ADAUGA</button>
</tbody>
</table>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
</body>
</html>
I know there is plenty of code above, but if you don't mind I would appreciate if you could explain shortly how to call splice function on my json products. Thanks again!

indexOf sometimes fails to find the index of an object in an array. Either you use lodash or underscore to do so, or change your approach:
<td><a ng-click="removeItem($index)">Remove</a></td>
Ctrl
$scope.removeItem = function(index) {
$scope.produse.products.splice(index, 1);
}
$index as available to you when using ng-repeat in angular.

You have a problem with myElement directive.
ng-click="removeItem(product)"
it should be
ng-click="removeItem(item)".

Related

jQuery - Filtering table using data attributes

I am trying to filter this table by data attributes, you can find it here:
http://jsfiddle.net/3nm5mz28/
I managed to get the value of the inputs with text using
$filters.on("keyup", function () {
var $i = $filters.filter(function () {
console.log(this.value);
return $.trim(this.value).length > 0;
})
});
Also was able to get data atributes of those input:
var datattrbs = $i.map(function () {
console.log($(this).val());
return $(this).data('column')
}).get().join(',');
The idea is to hide the rows which does not match all criteria on inputs, filtering by data attributes.
Right now I am stuck on this portion:
$rows.hide().filter(function () {
return $('td', this).filter('td[data-column='+datattrbs+']').filter(function () {
var content = this.textContent;
var inputVal = $i.filter($(this).data("column")).val();
return content.indexOf(inputVal) > -1;
}).length === len;
}).show();
UPDATE
I have managed to solve most issues, except filtering by many data attributes:
http://jsfiddle.net/vdbo47xv/
how can I filter by comma separated list: filter('td[data-column=id,articolo]')? is it possible?
You should change these parts in the code.
var inputVal = $i.filter($(this).data("column")).val();
to
$i.val(); // Get the value of typed value of input
and
$('td[data-column*=' + "id" + ']', this)
to
$('td[data-column=' + $i.attr("data-column") + ']', this) // Get the related data column
Complete code looks like;
var $rows = $('tbody > tr'),
$filters = $('#filter_table input');
$filters.on("keyup", function () {
var $i = $filters.filter(function () {
return $.trim(this.value).length > 0;
}),
len = $i.length;
if (len === 0) return $rows.show();
$rows.hide().filter(function () {
return $('td', this).filter('td[data-column='+ $i.attr("data-column") +']').filter(function () {
var content = this.textContent;
var column_info = $(this).data("column");
var inputVal = $i.filter('input[data-column='+column_info+']').val();
var values = inputVal.split(',');
var result = false;
for (index = 0; index < values.length; ++index) {
if(values[index] == "") continue;
result = content.indexOf(values[index]) > -1;
if(result == true)
{
break;
}
}
return result;
}).length === len;
}).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='products'>
<thead>
<tr id='filter_table'>
<th data-column='id'>Cod. prodotto
<br>
<input type='text' data-column='id' />
</th>
<th data-column='articolo'>Articolo
<br>
<input type='text' data-column='articolo' />
</th>
<th data-column='fornitore'>Fornitore
<br>
<input type='text' data-column='fornitore' />
</th>
<th data-column='nome'>Nome
<br>
<input type='text' data-column='nome' />
</th>
<th data-column='taglia'>Taglia
<br>
<input type='text' data-column='taglia' />
</th>
<th data-column='colore'>Colore
<br>
<input type='text' data-column='colore' />
</th>
<th data-column='prezzo_acquisto'>Prezzo acquisto
<br>
<input type='text' data-column='prezzo_acquisto' />
</th>
<th data-column='prezzo_vendita'>Prezzo vendita
<br>
<input type='text' data-column='prezzo_vendita' />
</th>
<th data-column='data'>Data
<br>
<input type='text' data-column='data' />
</th>
<th data-column='q'>Qta
<br>
<input type='text' data-column='q' />
</th>
<th data-column='qA'>QtaA
<br>
<input type='text' data-column='qA' />
</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column='id'>id</td>
<td data-column='articolo'>articolo</td>
<td data-column='fornitore'>fornitore</td>
<td data-column='nome'>nome</td>
<td data-column='taglia'>taglia</td>
<td data-column='colore'>colore</td>
<td data-column='prezzo_acquisto'>prezzo_acquisto</td>
<td data-column='prezzo_vendita'>prezzo_vendita</td>
<td data-column='data'>data</td>
<td data-column='q'>q</td>
<td data-column='qA'>qA</td>
</tr>
<tr>
<td data-column='id'>idx</td>
<td data-column='xarticolo'>articolo</td>
<td data-column='fornitore'>fornitorex</td>
<td data-column='nome'>nome</td>
<td data-column='taglia'>taglia</td>
<td data-column='colore'>colore</td>
<td data-column='prezzo_acquisto'>prezzo_acquisto</td>
<td data-column='prezzo_vendita'>prezzo_vendita</td>
<td data-column='data'>data</td>
<td data-column='q'>q</td>
<td data-column='qA'>qA</td>
</tr>
<tr>
<td data-column='id'>id</td>
<td data-column='articolo'>articolox</td>
<td data-column='fornitore'>fornitore</td>
<td data-column='nome'>nome</td>
<td data-column='taglia'>taglia</td>
<td data-column='colore'>colore</td>
<td data-column='prezzo_acquisto'>prezzo_acquisto</td>
<td data-column='prezzo_vendita'>prezzo_vendita</td>
<td data-column='data'>data</td>
<td data-column='q'>q</td>
<td data-column='qA'>qA</td>
</tr>
<tr>
<td data-column='id'>id</td>
<td data-column='articolo'>articolo</td>
<td data-column='fornitore'>fornitorex</td>
<td data-column='nome'>nome</td>
<td data-column='taglia'>taglia</td>
<td data-column='colore'>colore</td>
<td data-column='prezzo_acquisto'>prezzo_acquisto</td>
<td data-column='prezzo_vendita'>prezzo_vendita</td>
<td data-column='data'>data</td>
<td data-column='q'>q</td>
<td data-column='qA'>qA</td>
</tr>
</tbody>

Why my Angular js code is not working?

It is my code for angular js and html.Please help me about this.why it is not working with file if any error in syntax in html file or angular file?
I am trying to make a order table and I am doing it using angular js method and every time when I runs it on browser the Angular code is not working and Add button is also not working for me which is used to add the more entities in order.
angular.module('Commande', [])
.controller('commandeController', ['$scope', function($scope) {
$scope.articles = [
{ id: 1, reference: 123, titre: "MSI GTX 980ti", prixUnitaire: 666.63, quantite: 0, montantHT: 666.63, montantTTC: 799.95 },
{ id: 2, reference: 456, titre: "Intel Core i7-4770K", prixUnitaire: 324.96, quantite: 0, montantHT: 324.96, montantTTC: 389.95 },
{ id: 3, reference: 789, titre: "ASUS MAXIMUS VII RANGER", prixUnitaire: 134.96, quantite: 0, montantHT: 134.96, montantTTC: 161.95 }
];
$scope.PrixTotalTTC = function() {
var resultTTC = 0;
angular.forEach($scope.articles, function (article) {
resultTTC += article.montantTTC * article.quantite;
});
return resultTTC;
};
$scope.PrixTotalHT = function() {
var resultHT = 0;
angular.forEach($scope.articles, function (article) {
resultHT += article.montantHT * article.quantite;
});
return resultHT;
};
$scope.NombreArticle = function() {
var resultArticle = 0;
angular.forEach($scope.articles, function(article){
resultArticle += article.quantite;
});
return resultArticle;
};
$scope.AjouterArticle = function() {
$scope.articles.push({
id: '',
reference: '',
titre: '',
prixUnitaire: 0,
quantite: 0,
montantHT: 0,
montantTTC: 0
});
};
$scope.SupprimerArticle = function(index) {
$scope.articles.splice(index, 1);
};
}]);
<html lang="en-us">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.6.6/angular.min.js">
</script>
<script src="app.js"></script>
</head>
<body ng-app="Commande" ng-controller="commandeController">
<h1>Bon de commande</h1>
<div class="content">
<div class="col-md-12">
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<th>#</th>
<th>Référence</th>
<th>Titre</th>
<th>Prix unitaire HT/€</th>
<th>Quantité</th>
<th>Montant HT/€</th>
<th>Montant TTC/€</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="article in articles">
<th>
<input type="number" ng-model="article.id" class="form-control bfh-number" placeholder="Id" min=0>
</th>
<td>
<input type="number" ng-model="article.reference" class="form-control bfh-number" placeholder="Référence" min=0>
</td>
<td>
<input type="text" ng-model="article.titre" class="form-control" placeholder="Titre">
</td>
<td>
<input type="number" ng-model="article.prixUnitaire" class="form-control bfh-number">
</td>
<td>
<input type="number" ng-model="article.quantite" class="form-control bfh-number" min=0>
</td>
<td>
<input type="number" ng-model="article.montantHT" class="form-control bfh-number" min=0>
</td>
<td>
<input type="number" ng-model="article.montantTTC" class="form-control bfh-number" min=0>
</td>
<td>
<a href ng:click="SupprimerArticle($index)"><i class="fa fa-times delete"></i></a>
</td>
</tr>
<tr class="success">
<th class="success">TOTAL</th>
<td class="success"></td>
<td class="success"></td>
<td class="success"></td>
<td class="success">{{ NombreArticle() }} article(s)</td>
<td class="success" ng-style="PrixTotalHT() >= 1000 && {'font-weight': 'bold'}">{{ PrixTotalHT() | number:2 }} €</td>
<td class="success" ng-style="PrixTotalHT() >= 1000 && {'font-weight': 'bold'}">{{ PrixTotalTTC() | number:2 }} €</td>
<td class="success"></td>
</tr>
</tbody>
</table>
<a href ng:click="AjouterArticle()" class="btn btn-primary">Ajouter un article <i class="fa fa-plus"></i></a>
</div>
</div>
</body>
</html>
It is my code.
Sounds like you need a content management system (CMS), such as MAMP, XAMPP or similar. You basically need to run a local server for JavaScript code to work (as well as any PHP you might use). Simple solution, if just need JavaScript, is to use Node.js.

How to modify and update data table row in angular js?

I m learning of angular js and i have found i issue .
I m creating a new projects .
i have some button edit , add, remove,
if i click to my edit button than show all field but i want to show only current field than i click to update update this filed .
My code is here
Anguar
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
HTML Code is
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
table td, table th{
border:solid 1px red;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
If you only want one row to show the inputs on clicking its respective modify button you have two options:
1) Attach booleans to each of the JSON indexes of the tabelsData array.
2) Make a mirror array that houses these booleans.
Having two separate booleans in this case is useless, because each one is being treated on a toggle basis:
Here is the core code for doing approach number two since I assume you want your data to remain the same:
JS:
$scope.editingData = {};
for (var i = 0, length = $scope.tabelsData.length; i < length; i++) {
$scope.editingData[$scope.tabelsData[i].id] = false;
}
$scope.modify = function(tableData){
$scope.editingData[tableData.id] = true;
};
$scope.update = function(tableData){
$scope.editingData[tableData.id] = false;
};
Html:
<tbody>
<tr ng-repeat="tableData in tabelsData">
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.name | uppercase}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.dob}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.emailId}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.phone}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.address}}</div>
<div ng-show="editingData[tableData.id]">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="editingData[tableData.id]" ng-click="modify(tableData)">Modify</button>
<button ng-show="editingData[tableData.id]" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td>
</tr>
</tbody>
I made an example:
http://plnkr.co/edit/lXq1WB
Here is an example in Angular2, (this will NOT work for AngularJS!)
fichier.html:
<ng2-toasty [position]="'top-left'"></ng2-toasty>
<label for="trainingInput" class="mr-2">{{ 'LABEL.FORMATION' | translate }} :</label>
<table class="table table-hover table-striped table-sortable table-bordered">
<thead>
<tr>
<th *ngFor="let column of columns" [class]="selectedClass(column.variable)" (click)="changeSorting(column.variable)" translate>
{{column.display}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let object of data | orderBy : convertSorting(); let rowIndex = index">
<td *ngFor="let column of columns" class="{{column.variable}}-td">
<div *ngIf="!toUpdates[object['id']]" >{{object[column.variable] | format: column.filter}}</div>
<div *ngIf="toUpdates[object['id']]"><input type="text" [(ngModel)]="object[column.variable]" ></div>
</td>
<td class="text-center">
<i *ngIf="!toUpdates[object['id']]" class="fa fa-pencil-square-o edit-formation" aria-hidden="true" (click) = "editFormation(object)"></i>
<i *ngIf="toUpdates[object['id']]" class="fa fa-check-square-o save-edit-form" (click)="updateFormation(object)"></i>
<i class="fa fa-times" aria-hidden="true" (click)="deleteFormation(object['id'])"></i>
</td>
</tr>
<tr [hidden]="isDisabled()">
<td><input type="text" class="form-control" placeholder="Année" #years></td>
<td><input type="text" class="form-control" placeholder="Formation" #label></td>
<td><input type="text" class="form-control" placeholder="Durée" #duration></td>
<td class="text-center align-middle">
<i class="fa fa-plus-circle fa-2x" (click)="addFormation(years.value, label.value, duration.value)"></i>
</td>
</tr>
</tbody>
</table>
fichier.ts:
import {Component, Injector, Input, OnChanges, OnInit} from '#angular/core';
import { Http, Headers, RequestOptions, URLSearchParams } from '#angular/http';
import DynamicComponent from '../dynamic-component';
import Formation from './formation';
import {ToastyService, ToastyConfig, ToastOptions, ToastData} from 'ng2-toasty';
#Component({
moduleId: module.id,
selector: 'formations-selector',
templateUrl: './formations-template.html',
styleUrls: ['./formations-template.css'],
})
export default class FormationsComponent{
candidate: any = null;
listFormations: any = null;
candidateDetails: any = null;
columns: any[];
sort: any;
data: any[];
toUpdates: {};
constructor(private injector: Injector, private http: Http,private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
this.candidateDetails = this.injector.get('candidateDetails');
this.candidate = this.candidateDetails.candidate;
this.listFormations = this.candidateDetails.listFormations;
this.columns = this.listFormations.columns;
this.sort = this.listFormations.sort;
this.data = this.listFormations.data;
this.toastyConfig.theme = 'material';
this.toUpdates = {};
}
ngAfterViewInit(){
$(document).ready(function() {
/*
$('.edit-formation').click(function () {
var dad = $(this).parent().parent();
dad.find('td .duration-span').hide();
dad.find('td.duration-td').append('<input type="text" class="form-control" placeholder="Durée" value="'+dad.find('td .duration-span').html()+'" id = "duration-update" #durationu>');
dad.find('td .label-span').hide();
dad.find('td.label-td').append('<input type="text" class="form-control" placeholder="Formation" id="label-update" value="'+dad.find('td .label-span').html()+'" #labelu>');
dad.find('td .years-span').hide();
dad.find('td.years-td').append('<input type="text" class="form-control" placeholder="Année" id="years-update" value="'+dad.find('td .years-span').html()+'" #yearsu>');
dad.find('td.years-td').append('<i class="fa fa-check-square-o save-edit-form hidden" (click)="updateFormation(1, years.value, label.value, durationu)"></i>');
dad.find('td .edit-formation').addClass("hidden");
dad.find('td .save-edit-form').removeClass("hidden");
});
*/
/*
$('.save-edit-form').click(function () {
var dad = $(this).parent().parent();
dad.find('td .save-edit-form').addClass("hidden");
dad.find('td .edit-formation ').removeClass("hidden");
dad.find('td .duration-span').show();
$('#duration-update').remove();
dad.find('td .label-span').show();
$('#label-update').remove();
dad.find('td .years-span').show();
$('#years-update').remove();
});
*/
});
}
//Action déclenché lors d'un changement de société du candidat : on met à jour la liste des métiers associés
onChangeCompaniesInput(value) {
}
isDisabled(isDisabled) {
//return (isDisabled || !this.candidateDetails.isUserAuthorized) ? true : false;
}
selectedClass(columnName): string{
return columnName == this.sort.column ? 'sort-' + this.sort.descending : '';
}
changeSorting(columnName): void{
var sort = this.sort;
if (sort.column == columnName) {
sort.descending = !sort.descending;
} else {
sort.column = columnName;
sort.descending = false;
}
}
convertSorting(): string{
return this.sort.descending ? '-' + this.sort.column : this.sort.column;
}
onChangeMainFormaion(value): void{
console.log(value);
}
deleteFormation(idFormation): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
this.http.post('/api/formations/'+idFormation+'/deleteFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait supprmié avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
editFormation(tableData): void{
this.toUpdates[tableData['id']]= true;
}
updateFormation(tableData): void {
this.toUpdates[tableData['id']]= false;
console.log(tableData);
}
addFormation(years: string, label: string, durration: string, main: boolean = false): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
params.append('years', years);
params.append('label', label);
params.append('durration', durration);
params.append('main', main);
//let formation = new Formation(years, label, durration, false);
return this.http.post('/api/formations/'+this.candidate.id+'/addFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait ajouter avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Promise.reject(errMsg);
}
}

Javascript: Atributting value to an id What is wrong with this code?

the thing here is, i have this code, and it was supposed to output the results of the variables into contact form 7 for wordpress hidden fields (i have the modules plugin to enable the hidden fields) that were sent by email, but i dont think the id i display is getting the value i attribute, i js linted the code and all it said was multiple variable declaration, which shouldnt be a problem since it's an if statement, so, there will never be a double declaration of the variable.
This is the code i use to transform the cookies created in my script (using jQuery.cookie) into text that is outputted to a table in my website, but more than outputting it to a table, i would like to email it to the user, i already have a contact-form 7 form prepared to do this, i just need to attribute the value of the returned variable (or at least one of them, the last is the price, i dont need to send that by email) to the contact form field id, yesterday here in stackoverflow someone gave me that code to pass the value into contact form 7, but im afraid it isnt working :/
function readRims() {
var rims_read = $.cookie('rim_color');
if (rims_read=="black" ) {
var jantes = 'Pretas';
var preco = 'Sob Consulta';
}
else if (rims_read=="silver"){
var jantes = 'De Série';
var preco = '';
}
else if (rims_read=="white"){
var jantes = 'Brancas';
var preco = 'Sob Consulta';
}
else if (rims_read=="titanium"){
var jantes = 'Titanium';
var preco = 'Sob Consulta';
}
else {
var jantes = 'Escolha as Jantes';
var preco =' ';
}
$('#cfg_rims').val(jantes);
return {
jantes: jantes,
preco: preco
};
}
HTML
[hidden modelo id:cfg_model]
[hidden cor id:cfg_color]
[hidden jantes id:cfg_rims]
[hidden ac id:cfg_ac]
[hidden abs id:cfg_abs]
[hidden alarme id:cfg_alarm]
[hidden led id:cfg_led]
[hidden chapeleira id:cfg_chapeleira]
<p>Oferecemos a possibilidade de enviar um email à nossa equipa com as suas escolhas no nosso configurador como manifestação de interesse, preencha o seguinte formulário e carregue em enviar para proceder ao envio da informação, a nossa equipa entrará em contacto consigo para dar seguimento à manifestação de interesse.</p>
<p>O seu Nome<br/></p>
[text* nome]
<p>O seu Email<br/></p>
[email* email]
<p>Observações<br/></p>
[textarea obs]
<p>[submit "Enviar"]</p>
Try
<table class="tab_cfg" align="center" width="70%" cellspacing="0"
cellpadding="10">
<tr style="border-bottom: none;">
<th colspan="4"><br />
<p>Abra o Configurador e siga todos os passos, a tabela abaixo
vai mostrar os resultados que escolheu:</p></th>
</tr>
<tr>
<th colspan="4"><a class="readon"
href="http://popo.com.pt/POPO/configurador/cfg/page_model/configurador_model.html"
rel="rokbox[550 600]">Configurador</a> <a class="readon"
href="javascript:setCookies(); document.location.reload(true)">Reset</a>
</th>
</tr>
<tr>
<td colspan="2"> </td>
<td>Característica</td>
<td>Preço</td>
</tr>
<tr>
<td colspan="2">Modelo</td>
<td><p class="modelo-modelo"></p></td>
<td><p class="modelo-preco"></p></td>
</tr>
<tr>
<td colspan="2">Cor</td>
<td><p class="color"></p></td>
<td></td>
</tr>
<tr>
<td colspan="2">Jantes</td>
<td><p class="rims-jantes"></p></td>
<td><p class="rims-preco"></p></td>
</tr>
<tr>
<td style="border-right: 1px solid #d1d1d1;" rowspan="6">Extras</td>
<td>ABS</td>
<td><p class="abs-abs"></p></td>
<td><p class="abs-preco"></p></td>
</tr>
<tr border="1px">
<td>Ar Condicionado</td>
<td><p class="ac-ac"></p></td>
<td><p class="ac-preco"></p></td>
</tr>
<tr>
<td>Alarme</td>
<td><p class="alarm-alarm"></p></td>
<td><p class="alarm-preco"></p></td>
</tr>
<tr>
<td>Luzes LED</td>
<td><p class="led.led"></p></td>
<td><p class="led.preco"></p></td>
</tr>
<tr style="border-bottom: none;">
<td>Chapeleira</td>
<td><p class="chapeleira-chapeleira"></p></td>
<td><p class="chapeleira-preco"></p></td>
</tr>
</table>
<script type="text/javascript">
jQuery(function($) {
var $table = $('.tab_cfg');
var modelo = readModel();
$table.find('.modelo-modelo').html(modelo.modelo)
$table.find('.modelo-preco').html(modelo.preco)
$table.find('.color').html(readColor())
var jantes = readRims();
$table.find('.rims-jantes').html(jantes.modelo)
$table.find('.rims-preco').html(jantes.preco)
var abs = readABS();
$table.find('.abs-abs').html(abs.modelo)
$table.find('.abs-preco').html(abs.preco)
var ac = readAC();
$table.find('.ac-modelo').html(ac.modelo)
$table.find('.ac-preco').html(ac.preco)
var alarm = readAlarm();
$table.find('.alarm-modelo').html(alarm.modelo)
$table.find('.alarm-preco').html(alarm.preco)
var led = readLED();
$table.find('.led-modelo').html(led.modelo)
$table.find('.led-preco').html(led.preco)
var chapeleira = readChap();
$table.find('.chapeleira-modelo').html(chapeleira.modelo)
$table.find('.chapeleira-preco').html(chapeleira.preco)
})
</script>

jquery form validation not fired / working

I need to do a very basic form validation, and my method of choice is jQuery. However, for some reason, the validation function seems not to get fired at all.
After looking at this for several hours I can't find out what the problem is.
HTML:
<form id="form1" name="form1" method="post" action="process.php">
<table width="100%" border="0" cellspacing="5" cellpadding="0">
<tr>
<td width="160">Meno:</td>
<td><input type="text" name="meno" id="meno" /></td>
<td width="160">Priezvisko:</td>
<td><input type="text" name="priezvisko" id="priezvisko" /></td>
</tr>
<tr>
<td width="160">Názov spolocnosti: <br />
<span class="register_comment">(nevyplnajte ak nie ste podnikatel)</span></td>
<td><input type="text" name="spolocnost" id="spolocnost" /></td>
<td width="160">Krajina:</td>
<td><select name="krajina" id="krajina">
<option value="" selected="selected"> </option>
<option value="cz">Ceská republika</option>
<option value="sk">Slovenská republika</option>
</select></td>
</tr>
<tr>
<td width="160">Adresa:</td>
<td><input type="text" name="adresa" id="adresa" /></td>
<td width="160">Mesto:</td>
<td><input type="text" name="mesto" id="mesto" /></td>
</tr>
<tr>
<td width="160">Email:<br />
<span class="register_comment">(na tento email Vám príde potvrdenie)</span></td>
<td><input type="text" name="email" id="email" /></td>
<td width="160">Telefonický kontakt:<br />
<span class="register_comment">(uvádzajte kontakt na mobilný telefón na ktorom budete zastihnutelní najmä 10.10.!)</span></td>
<td><input type="text" name="telefon" id="telefon" /></td>
</tr>
<tr>
<td width="160">Miesto nástupu: </td>
<td colspan="3"><select name="nastup" id="nastup">
<option value="" selected="selected"> </option>
<option value="nr">Nitra</option>
<option value="ba">Bratislava</option>
<option value="br">Brno - Avion Shopping Park, Škandinávská 128/2</option>
<option value="ph">Praha - Avion Shopping Park, Škandinávská 15/A</option>
<option value="pl">Plzen - OC Olympia, Písecká 972/1</option>
</select></td>
</tr>
<tr>
<td colspan="4"><p>
<label>
<input type="checkbox" name="suhlas" value="checkbox" id="suhlas" />
Oboznámil som sa s podmienkami úcasti a Súhlasím s podmienkami úcasti </label>
FLEX Polishing Camp<br />
</p></td>
</tr>
<tr>
<td colspan="4" align="center"><input type="submit" id="button" value="Odoslat záväznú prihlášku na FLEX Polishing Camp" style="width:500px;" /></td>
</tr>
<tr>
<td colspan="4" class="register_comment">xxxx</td>
</tr>
</table>
</form>
jQuery:
<script>
$("#form1").submit(function() {
var errors = new array();
if ($('input[name=meno]').val() == "") {
errors.push('Meno je povinná položka.');
}
if ($('input[name=priezvisko]').val() == "") {
errors.push('Priezvisko je povinná položka.');
}
if ($('input[name=krajina]').val() == "") {
errors.push('Je nutné vybrať si krajinu - ČR alebo SR.');
}
if ($('input[name=adresa]').val() == "") {
errors.push('Adresa je povinná položka.');
}
if ($('input[name=mesto]').val() == "") {
errors.push('Mesto je povinná položka.');
}
if ($('input[name=email]').val() == "") {
errors.push('Email je povinná položka.');
}
if ($('input[name=telefon]').val() == "") {
errors.push('Telefonický kontakt je povinná položka.');
}
if ($('input[name=nastup]').val() == "") {
errors.push('Telefonický kontakt je povinná položka.');
}
if (!$('#suhlas').attr('checked')) {
errors.push('Je potrebné vysloviť súhlas s podmienkami zaškrtnutím tlačítka "Oboznámil som sa s podmienkami účasti a Súhlasím s podmienkami účasti FLEX Polishing Camp".');
}
if ( errors.lenght > 0 )
{
var text;
for (var i = 0; i < errors.length; i++) {
text = text + errors[i] + '\n';
};
alert(text);
return false;
}
return true;
});
</script>
$("form1") should be $("#form1")
As other mention you have missed the # for your ID selector, you can also use map method and minify your code.
$("#form1").submit(function() {
var errors = [];
errors = $('input[type=text]', this).filter(function(){
return $.trim(this.value) == "";
}).map(function() {
return this.name + ' je povinná položka.';
}).get();
if (errors.length) {
var text = errors.join('\n');
alert(text);
return false;
}
});
http://jsfiddle.net/bwVWQ/
First $("form1") should be $("#form1")
//Secondly
text = text + arr[i] + '\n';
//Should be
text = text + errors[i] + '\n'; OR text += errors[i] + '\n';
Looks like the Updated code has again a typo in it..
This might be preventing it
if ( errors.lenght > 0 ) // Supposed to be errors.length
You are missing the # sign on your selector, #form1
$("#form1").submit(function() {

Categories