javascript - Validate the input field for existing item in object array? -


in todo list dont want user input same todos again again... problem is, when enter example (test) first time , enter (test2) , enter (test) again, taking value.... how validate properly....

fiddle https://jsfiddle.net/lal7h6lv/1/

html

<div ng-app="todoapp" ng-controller="mainctrl">         <ul>           <li ng-repeat="todoitem in todoitems">{{todoitem.name}}</li>         </ul>     <form ng-submit="additem()">         <input type="text" ng-model="newitem">         <input type="submit" name="go">     </form>     </div> 

angularjs

angular.module("todoapp", []) .controller('mainctrl', ['$scope', function($scope){    $scope.todoitems = [{'name' : 'akshay'}];   $scope.test = false;    $scope.additem = function(){       if($scope.newitem){           $scope.checkrepeattodo();           if($scope.test == true){               $scope.todoitems.push({'name':$scope.newitem});               $scope.newitem = '';           }else{               alert('same todo');               $scope.test = false;           }       }else{           alert('fill form');       }   };    $scope.checkrepeattodo = function(){       $scope.todoitems.filter(function(item){           if($scope.newitem === item.name){               $scope.test = false;           }else{               $scope.test = true;           }       });   }; }]); 

the issue $scope.test value, override value true when filters down 3rd item.

see working fiddle

alternative:

make javascript function rather 1 in $scope , call function return if valid entry or not.

this eliminates need have $scope.test , $scope.checkrepeattodo nothing of importance.

function checkrepeattodo() {   var valid = true;      $scope.todoitems.filter(function(item){        if($scope.newitem === item.name){             return valid = false;         }     });   return valid; }; 

and use same as:

if(checkrepeattodo()){     $scope.todoitems.push({'name':$scope.newitem});     $scope.newitem = ''; } else{  alert('same todo'); } 

demo here


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -