1

I want to restrict the user to create a new text box and echo error message , if he/she inputs same value in the previous text field. Therefore only create a new text box if the text fields has different values.

HTML

<input type="text" ng-model="set.values"/>
<span ng-show="message"> Please enter a different value </span> 

ANGULARJS

$scope.set = { values: [] };
$scope.message = false; 

$scope.add = function (){
    $scope.message = false; 
    $scope.set.values.push(''); 
}
1
  • $scope.set.push(''); How is it working? It should be like $scope.set.values.push(''), Please post complete required code for that problem. Commented Aug 18, 2017 at 11:06

3 Answers 3

4

You can use indexOf and $watch. Watch the ng-model value for change and check if that value already exists in the array, if so throw error.

HTML

<input type="text" ng-model="set.val"/>
<span ng-show="message"> Please enter a different value </span> 

JS

$scope.set = {
     values: []
 }; //array that contains previous ng-model values
 $scope.message = false;
 $scope.$watch('set.val', function(val) {
     if (val != undefined) var index = $scope.set.values.indexOf(val);
     if (index > -1) $scope.message = true;
     else {
         $scope.message = false;
         $scope.set.values.push(val);
         //add new input logic
     }
 })

Update

If you want the check to happen after clicking a add button(which I assume is present in your UI)

$scope.set = {
    values: [] //array that contains previous ng-model values
};
$scope.add = function() {
    var index = $scope.set.values.indexOf($scope.set.val);
    if (index > -1) $scope.message = true;
    else {
        $scope.message = false;
        $scope.set.values.push($scope.set.val);
        //add new input logic
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

I think the logic should be inside the add function instead of watch?
It is not clear from the question on how add is invoked and whether the error message should be thrown before clicking add. I will update answer with add button
@Vivz, First of all, sorry for late reply, I was in holiday :). I would prefer the code where you have stated Update in bold. I tried the code but doesn't work. First time index = undefined so it creates a empty text (PASS). Second time, when I insert a value in the text field and click add, index = 0 so it gives me message (FAIL).
Are you filling anything in your input and clicking add button, otherwise you could keep one outer check if($scope.set.val!=undefined|| $scope.set.val!="")
So first time index will be undefined and it will go into else part where the data will be pushed into $scope.set.values. Second time the check will ensure if the value is present in the array. If it is present , it will return the index of the position of the value, else it is not present and will go to the else part where it will be pushed into the array
2

See this, if you wish to restrict the user to create a new text box and echo error message when he/she inputs same value in the previous text field.

var app = angular.module("app", []).controller("ctrl", function($scope) {

  $scope.boxes = [{value: ""}];
  $scope.message = false;

  $scope.add = function(val) {
    $scope.message = false;   
    //If total boxes are just one, no need to check, just set the value a nd insert a new box
    if ($scope.boxes.length == 1) {
      $scope.boxes[0].value = val;
      $scope.boxes.push({value: ""});
    } 
    //Total boxes are greater than 1, check last entered value and then add box
    else {
      $scope.checkAndAddBox(val);
    }
  }

  $scope.checkAndAddBox = function(val) {
    // $scope.boxes.length - 2 will give the last box from which value has to be checked
    var lastBoxValue = $scope.boxes[$scope.boxes.length - 2].value;
    //check this value with the new input box value
    if (val != lastBoxValue) {
      //set the box to this value
      $scope.boxes[$scope.boxes.length - 1].value = val;
      //insert a new one 
      $scope.boxes.push({value: ""});
    } 
    //box has the same value, show error message
    else {
      $scope.message = true;
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <div ng-repeat="box in boxes track by $index">
    <input type="text" ng-model="box.value" ng-readonly="$last ? false : true" />
    <button ng-if="$last" ng-click="add(box.value)">Add</button>
  </div>
  <span ng-show="message"> Please enter a different value </span>
</body>

Comments

0

JS CODE : 

var akashApp = angular.module('akashApp',[]);
          function AvoidDuplicateEntries($scope){
          $scope.books = [
          {bookname: 'Learn Angular'},
          {bookname: 'JS Tutorial'},
          {bookname: 'Node Basics'}
          ];
          var someBook = $scope.books;
          $scope.addBook = function (){
          var newBook = $scope.bookname;
          var oldbooks;
          if(newBook){ // avoiding empty data
          angular.forEach($scope.books, function(eachbook){ //For loop
          if(newBook.toLowerCase() == eachbook.bookname.toLowerCase()){ // this is for checking whether the data is existing or not
          oldmovies = true;
          }
          });
          if(!oldbooks){
          someBook.push({bookname:newBook});
          }
         }
        }
       }
		  
You can try this also.

HTML CODE : 

<div style="padding:20px" ng-app="akashApp" id="ng-app" ng-controller="AvoidDuplicateEntries">
<h1>Basics using AngularJS</h1>
<table class="table table-bordered" style="width:220px;">
<thead>
<tr><td>#</td>
<td>Book Name</td></tr>
</thead>
<tr ng-repeat='Book in Racks'>
<td>{{$index+1}}</td>
<td>{{book.bookname}}</td>
</tr>
</table>
<form ng-submit="addBook();">
<input type="text" ng-model="bookname" size="30" placeholder="Which book you want to read" /><br />
<input type="submit" class="btn btn-primary" value="Add Book">
</form>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.