Angular JS filter Search - javascript

I want to retain the selected check boxes as is even when I am
changing my search query. Initially I am posting some query in search
and selecting one of the resulted values, Now if I change my search
query, then New values will be my result. But I want to retain the
checkbox selected for the previous values...
`
//Demo of Searching and Sorting Table with AngularJS
var myApp = angular.module('myApp',[]);
myApp.controller('TableCtrl', ['$scope', function($scope) {
$scope.allItems = getDummyData();
$scope.resetAll = function()
{
$scope.filteredList = $scope.allItems ;
$scope.newEmpId = '';
$scope.newName = '';
$scope.newEmail = '';
$scope.searchText = '';
}
$scope.add = function()
{
$scope.allItems.push({EmpId : $scope.newEmpId, name : $scope.newName, Email:$scope.newEmail});
$scope.resetAll();
}
$scope.search = function()
{
$scope.filteredList = _.filter($scope.allItems,
function(item){
return searchUtil(item,$scope.searchText);
});
if($scope.searchText == '')
{
$scope.filteredList = $scope.allItems ;
}
}
$scope.resetAll();
}]);
/* Search Text in all 3 fields */
function searchUtil(item,toSearch)
{
/* Search Text in all 3 fields */
return ( item.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.Email.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.EmpId == toSearch
)
? true : false ;
}
/*Get Dummy Data for Example*/
function getDummyData()
{
return [
{EmpId:2, name:'Jitendra', Email: 'jz#gmail.com'},
{EmpId:1, name:'Minal', Email: 'amz#gmail.com'},
{EmpId:3, name:'Rudra', Email: 'ruz#gmail.com'}
];
}
.icon-search{margin-left:-25px;}
<br /> <br />
<div ng-app="myApp">
<div ng-controller="TableCtrl">
<div class="input-group">
<input class="form-control" ng-model="searchText" placeholder="Search" type="search" ng-change="search()" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
</div>
<table class="table table-hover data-table sort display">
<thead>
<tr>
<th class="EmpId"> <a href="" ng-click="columnToOrder='EmpId';reverse=!reverse">EmpId
</a></th>
<th class="name"> Name </th>
<th class="Email"> Email </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in filteredList | orderBy:columnToOrder:reverse">
<td><input type="checkbox" name="test" />{{item.EmpId}}</td>
<td>{{item.name}}</td>
<td>{{item.Email}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-xs-3">
<input type="text" ng-model="newEmpId" class="form-control" placeholder="EmpId">
</div>
<div class="col-xs-3">
<input type="text" ng-model="newName" class="form-control" placeholder="Name">
</div>
<div class="col-xs-4">
<input type="email" ng-model="newEmail" class="form-control" placeholder="Email">
</div>
<div class="col-xs-1">
<button ng-click="add()" type="button" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</div> <!-- Ends Controller -->
</div>
`Fiddle

Try to add ng-model="item.selected" to your checkbox tag
<td><input ng-model="item.selected" type="checkbox" name="test" />{{item.EmpId}}</td>
Works for me, hope it helps.

Looks like this is happening because you are resetting the items here:
if($scope.searchText == '')
{
$scope.filteredList = $scope.allItems ;
}
and allItems doesn't tell anywhere if the checkbox needs to be selected on not. I would suggest you to update the code where you are creating the checkboxes, something like:
<td><input type="checkbox" name="test" ng-model=item.selected ng-checked=item.selected/>
Note that I have updated the item to have a 'selected' field which will tell if that item is selected or not(default could be false). While creating the checkbox I have linked the model using ng-model=item.selected
Updated fiddle at http://jsfiddle.net/3a3zD/194/

Related

Get the value of inputs and convert them to a certain array format

I'm trying to get the value of all input that is located in a table header created using ng-repeat upon clicking a button.
This is my html code for creating all the inputs
<th ng-repeat="(index, header) in filterTbl.gatVisibleFilterHeaders track by $index"
style="display: {{header.is_visible ? 'block' : 'none'}};
width: {{filterTbl.gatFilterHeadersWidth}}px !important;">
<div>
<span class="field-{{ header.filter_type }} th-title">{{ header.name }}</span>
<span class="fa fa-filter header-filter spanHF-{{index}}" title="Filter"
ng-click="filterTbl.showFilter(index, $event)" role="button"
tabindex="0"></span>
</div>
<div class="actual-filter divAF-{{index}} filter_input">
<input type="hidden" value="{{ header.col }}" class="header_col"
name="filter_header_col" />
<div ng-if="header.filter_type == 'text' || header.filter_type == ''"
ng-click="filterTbl.getFilterRecords(index, header)">
<div class="filter_select_container_{{ index }}"
style="display: block">
<select class="form-control select2 filter_{{ index }}"
name="filter_select" multiple="multiple">
</select>
</div>
</div>
<div ng-if="header.filter_type == 'numeric'">
<div class="number-range">
<div style="display: none;" class="filter-numeric-error"></div>
<input type="text" class="form-control froms "
onclick="event.stopPropagation();"
placeholder="From"
pattern="[0-9]{1,14}\.[0-9]{2}"/>
<div class="clearfix"></div>
</div>
<div class="number-range">
<div style="display: none;" class="filter-numeric-error"></div>
<input type="text" class="form-control to"
onclick="event.stopPropagation();"
placeholder="To" pattern="[0-9]{1,14}\.[0-9]{2}"/>
<div class="clearfix"></div>
</div>
</div>
</div>
</th>
I successfully created all the select tag and inputs but being able to pass them properly on javascript side.
This is my function when i click a button to get all the value of created input
var filterSelect = [];
$('#filterTable').find('table input,table select,table textarea').each(function(item, value) {
// console.log(item, value);
console.log(this.value);
});
I'm successfully receiving the value of a select but I need to convert it to a result something like this
['name of input': value, 'name of input': value]
example : [col:1, filter_select: "sample"]
Does anybody has an idea how can I accomplish this. been stuck for 1 week already.
Did you try to have array in which you push the values selected from select ? Your modified function will be as follows
filterSelect = [];
$('#filterTable').find('table input,table select,table
textarea').each(function(item, value) {
var obj={item:value};
this.filterSelect.push(obj);
//to verify the array items
angular.forEach(this.filterSelect, function(value, key) {
console.log(key + ': ' + value);
});
});

How to prevent adding existing email to table row in angularjs

I want to prevent adding an email address which already exists.
I want to disable adding more than 5 email addresses and names.
This is controller.js:
var helloApp = angular.module("helloApp", []);
helloApp.controller("CompanyCtrl", function($scope) {
$scope.companies = [
{ 'name':'Infosys Technologies',
'email': 'firstdawn1994#gmail.com',},
{ 'name':'Cognizant Technologies',
'email': 'cognizant#gmail.com',},
{ 'name':'Wipro',
'email': 'wipro#gmail.com',},
{ 'name':'Tata Consultancy Services (TCS)',
'email': 'tata#gmail.com',},
{ 'name':'HCL Technologies',
'email': 'hcl#gmail.com',},
];
$scope.addRow = function(){
$scope.companies.push({ 'name':$scope.name, 'email': $scope.email });
$scope.name='';
$scope.email='';
};
$scope.removeRow = function(name){
var index = -1;
var comArr = eval( $scope.companies );
for( var i = 0; i < comArr.length; i++ ) {
if( comArr[i].name === name ) {
index = i;
break;
}
}
if( index === -1 ) {
alert( "Something gone wrong" );
}
$scope.companies.splice( index, 1 );
};
});
This is the HTML:
<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="js/controllers.js"></script>
</head>
<!-- Controller name goes here -->
<body ng-controller="CompanyCtrl">
<input type="submit" value="Add New User +" class="btn btn-primary" id="add_user" />
<form class="form-horizontal" role="form" ng-submit="addRow()" id="submit_form">
<div class="form-group">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-4">
<input type="text" class="form-control" name="name"
ng-model="name" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Email</label>
<div class="col-md-4">
<input type="text" class="form-control" name="email"
ng-model="email" />
</div>
</div>
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Submit" class="btn btn-primary"/>
</div>
</div>
</form>
<table class="table">
<tr>
<th>Name
</th>
<th>Email
</th>
</tr>
<tr ng-repeat="company in companies | limitTo : 5">
<td>{{company.name}}
</td>
<td>{{company.email}}
</td>
<td>
<input type="button" value="Remove" class="btn btn-primary" ng-click="removeRow(company.name)"/>
</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$('#submit_form').hide();
$('#add_user').click(function(event) {
$('#submit_form').toggle(1000);
});
});
</script>
</body>
</html>
To achieve this please modify your addRow function to this code below
$scope.addRow = function(){
//store the new company in a variable for easy reference
var newCompany = { 'name':$scope.name, 'email': $scope.email };
//loops through existing companies to check if the email exists already
var emailExists = $scope.companies.some(function(item){
return item.email === newCompany.email;
});
//validation check before inserting the new company.
if( $scope.companies.length < 5 && !emailExists){
$scope.companies.push(newCompany);
$scope.name='';
$scope.email='';
}else{
//display some validation messages
}
};
Also in your HTML, you can disable the Add button so that the user does not have the opportunity to add more Companies if you already have up to 5 companies by adding the attribute below the button to:
data-ng-disable="companies.length > 5"
Hence, the button becomes:
<input type="submit" data-ng-disable="companies.length > 5" value="Submit" class="btn btn-primary"/>
Hope this helps

How do I change the input name in jQuery

This is what I am currently trying to achieve:
I am trying to clone a form and change the input name. How would I pull this off.
JS:
$(document).ready(function() {
var counter = 0;
var MAX_FIELDS = 3;
var MIN_FIELDS = 1;
var form = $('.force-group');
$('#add').on('click', function(e) {
if (counter < MAX_FIELDS) {
//$(".form-group").clone().appendTo("#forceForm");
$.each(form, function(i) {
var clone = $('.force-group').first().clone();
clone.children().val("");
$(this).parent().append(clone);
if (counter == 0) {
$("b:eq(1)").html("<b> Force 2</b>");
};
if (counter == 1) {
$("b:eq(3)").html("<b> Force 3</b>");
};
if (counter == 2) {
$("b:eq(5)").html("<b> Force 4</b>");
};
});
counter++;
};
});
html:
<#import "template.ftl" as layout />
<#layout.template title="Force" js="/js/force.js" css="/css/force.css">
<h3 class = "text-center">Total Force</h3>
<hr>
<div class="col-md-6 col-md-offset-3 col-xs-8 col-xs-offset-2">
<div class="force-selector input_fields_wrap">
<a id = 'add' href="#" class="btn btn-primary col-md-5">Add Force</a>
<a id = 'remove' href="#" class="btn btn-warning col-md-5 col-md-offset-2">Remove Force</a>
</div>
</div>
<div class="col-md-6 col-md-offset-">
<div class="col-xs-12">
<div class = "well" id="force-input">
<form id = "forceForm" class = "form-horizontal" method = "POST" autocomplete="off">
<fieldset>
<h4 class="text-center" id="form-title"><strong>Input</strong></h4>
<div class="form-group force-group">
<label class = "control-label col-md-2"><b>Force 1</b></label>
<label class = "control-label col-md-2">Magnitude</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0force" autocomplete="off">
</div>
<label class = "control-label col-md-2">Angle</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0angle" autocomplete="off">
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class = "col-md-5">
<table id = "forceChart" class="table table-striped table-hover">
<thead>
<tr class="table">
<th class="head-pad">Total Force</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td class="pad">Net Force:</td>
</tr>
</tbody>
</thead>
<tbody>
<tr class="table">
<td class="pad">Direction:</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class = "col-md-4 col-md-offset-4 col-xs-6 col-xs-offset-3">
<div class="form-group">
<div class = "col-md-6 col-xs-offset-3">
<input id = "calculate" class = "btn btn-success btn-block" type="submit" value="Calculate!">
</div>
</div>
</div>
This is the jsfiddle link right here:
Click here for the link.
PS: I am using a templater so the jsfiddle will look kinda bad.
I am new to jQuery and I have been searching around a solution but I seem to get stuck with it.
I tried using the .last() with the attr edit but that seems not to do anything.
To change an input name just use attr() method
$('input').attr('name', 'yourNewname');
and I remarque that you have input without Id so you should use one of those methods:
1/ give each input an Id for example #input1 #input2
$('#input1').attr('name', 'yourNewname1'); // change the name of first input
$('#input2').attr('name', 'yourNewname2'); // change the name of first input
or
you can use eq()
$('input').eq(0).attr('name', 'yourNewname1'); // change the name of first input
$('input').eq(1).attr('name', 'yourNewname2'); // change the name of first input
To change any attribute including name you can do this
$('#myInputFieldId').attr('name','new_name')
Hope it helps
Try this: $('input[name="0angle"]').attr('name', 'new-name');

Angular error : Expected array but received: 0

I'm getting this error when I open up a model partial:
<form action="" novalidate name="newGroupForm">
<div class="modal-body">
<div class="row">
<!-- SELECT THE NUMBER OF GROUPS YOU WANT TO CREATE -->
<label>Select number of groups</label>
<a class="btn" ng-click="newGroupCount = newGroupCount + 1" ng-disabled="newGroupCount == 10" ><i class="fa fa-plus-circle"></i></a>
<input class="groupCounter input-sm" ng-model="newGroupCount" type="number" min="1" max="10" disabled>
<a class="btn" ng-click="newGroupCount = newGroupCount - 1" ng-disabled="newGroupCount == 1"><i class="fa fa-minus-circle"></i></a>
</div>
<br>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Group Name</th>
<th>Group Description (optional)</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in getNumber(newGroupCount) track by $index">
<td>{{$index+1}}</td>
<td>
<input class= input-sm type="text" required="true" autofocus="true" placeholder="Group name" ng-model="groupData.title[$index]">
</td>
<td>
<input class="form-control input-sm" type="textarea" ng-model="groupData.desc[$index]" placeholder="Group Description">
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" type="submit" ng-click="submit()" ng-disabled="newGroupForm.$invalid">Create</button>
</div>
</form>
The modal controller looks like this:
spApp.controller('newGroupCtrl',
function newGroupCtrl($scope, $uibModalInstance, GroupService){
$scope.groupData = {
title: [],
desc: []
}
$scope.newGroupCount = 1;
$scope.getNumber = function(num) {
//console.log(num);
return new Array(num);
}
$scope.submit = function(){
$uibModalInstance.close($scope.groupData);
}
$scope.cancel = function (){
$uibModalInstance.dismiss('Cancelled group creation');
};
}
);
Every question I've seen refers to the use of filterbut I'm not using filter. The error repeats whenever I hit the increment button:
<a class="btn" ng-click="newGroupCount = newGroupCount + 1" ng-disabled="newGroupCount == 10" ><i class="fa fa-plus-circle"></i></a>
$scope.getNumber calls new Array(num), which will return an array of undefined values directly proportional to the value of newGroupCount.
For example:
new Array(5) // => [undefined, undefined, undefined, undefined, undefined]
Browsers don't handle that well, since it appears to be an empty array.
You're using ng-repeat in a way that it wasn't quite meant to be used. If I were you, I'd refactor to look something like this:
$scope.groups = [];
$scope.addGroup = function() {
// implement this, and use it in your button that increments the groups
$scope.groups.push(/* whatever */);
}
$scope.removeGroup = function() {
// implement this to remove a group
$scope.groups.splice(/* whatever */);
}
Then in your HTML:
<tr ng-repeat="group in groups">
<!-- display group info -->
</tr>
It may make your life easier here to work with angular (use it how it was intended) instead of fighting against how ng-repeat is meant to work.
The data is generally meant to be in the form of a collection (i.e. [{},{},{}]). Formatting it as such will make it easier for you. See the docs for ng-repeat.

angularjs $valid not working on fields

I am new to angularjs.
I have 2 buttons on my form and one is Save and other is Test Connection button.
<td align="left" colspan="0" >
<input class="form-control" title="Specifies the IP address of the SIP trunk ethernet connection." placeholder="xxx.xxx.xxx.xxx"
style="display: inline-block;display:block;white-space: nowrap;overflow: hidden;" type="text"
name="pabxipaddress" id="pabxipaddress" ng-model="userSetup.pabxipaddress" required ng-pattern='patternPresent' >
</td>
<td>
<span class="error" ng-show="(testIPOfficeFlag || submitted) && userSetupForm.pabxipaddress.$error.required">
<label style="color: red;">Required!</label>
</span>
<span class="error" ng-show='(testIPOfficeFlag || submitted) && userSetupForm.pabxipaddress.$error.pattern'>
<label style="color: red;">Invalid IP Address!</label>
</span>
</td>
Now in my JS file when I do like,
$scope.userSetup.pabxipaddress.$valid for some dynamic testing it gives me
TypeError: Cannot read property '$valid' of undefined
when I alert like $scope.userSetup.pabxipaddress it displays the data correctly.
How to check whether individual field is correct and passed all constraints attached to it.
The valid property is not part of the model value... try
$scope.userSetupForm.postdail.$valid
where userSetupForm is the name of the form and postdail is the name of the input element.
var app = angular.module('my-app', [], function() {
})
app.controller('AppController', function($scope) {
$scope.check = function() {
$scope.validity = {
field1: $scope.myform.myfield1.$valid,
field2: $scope.myform.myfield2.$valid,
field3: $scope.myform.myfield3.$valid
}
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
<form name="myform" novalidate>
<div>
<input type="number" name="myfield1" ng-model="formdata.myfield1" required class="numbers-only-for" minvalue="1" maxvalue="45">
</div>
<div>
<input type="text" name="myfield2" ng-model="formdata.myfield2" required>
</div>
<div>
<input type="text" name="myfield3" ng-model="formdata.myfield3" required>
</div>
<button ng-click="check()">Check</button>
</form>
<pre>{{formdata | json}}</pre>
<pre>{{validity | json}}</pre>
</div>

Categories

Resources