Discovering if a value has been entered into an input field in AngularJS can be achieved by verifying its availability

Is there a way to check if the value entered in an input field is already in a specified array? I would like to validate the input field value on key press against an array of names and display an error message if the value is already present in the array. Additionally, I want to disable the button. If the entered value is not in the array, I do not want to display an error message and want to enable the button. You can view the example on Plunkr here.

Here is the HTML code:

<!DOCTYPE html>
<html>

  <head>
    <script src="angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>

  </head>

  <body ng-app="test" ng-controller="testController">
   Name: <input type="text"/>
   <button on-keypress="submit()">Add</button>
  </body>

</html>

And here is the script:

var testController = angular.module('test', []);

testController.controller('testController', ['$scope', function($scope) {

  $scope.names = ["name1","name2","name3"];

  angular.forEach($scope.names, function(x) {

    console.log(x);
  });
}]);

Answer №1

To avoid looping through the array every time, it is recommended to utilize ng-change and validate for duplicates using array.prototype.includes().

Check out the Updated Plunkr

HTML:

<body ng-app="test" ng-controller="testController">
  Name: <input type="text" ng-change="checkName()" ng-model="name"/>
  <button ng-keypress="submit()">Add</button>
  <p ng-show="showError">Name already exists</p>
</body>

Controller:

$scope.names = ["name1", "name2", "name3"];
$scope.showError = false;

$scope.checkName = function() {
  if ($scope.names.includes($scope.name)) {
    $scope.showError = true;
  } else {
    $scope.showError = false;
  }
}

Answer №2

<body ng-app="test" ng-controller="testController">
   Name: <input type="text" id="getValue"/>
   <button on-keypress="submit()">Add</button>
  </body>

Employed an id attribute above to fetch value from the text field

$scope.names = ["name1","name2","name3"];

  for (i = 0; i < $scope.names.length; i++) {
    if (document.getElementById('getValue').value === $scope.names[i]) {
         alert('something'); 
         return;
    };
  };

Executed a function to validate names in the array and display an alert if found.

To conceal, apply a class to

<button on-keypress="submit()" class="random">Add</button>
and trigger it from the controller $('.random').hide();, noting that JQuery is utilized here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging elements in HTML for Manipulating with JavaScript

I haven't started coding yet, but I'm contemplating the overall strategy. My front end is primarily composed of HTML tables, giving it an Excel-like appearance. I am considering generating default pages and then using JavaScript to dynamically m ...

What is the proper way for the curry function to function effectively?

Here's a function that I came across: function curry(fn) { var args = [].slice.call(arguments, 1); return function() { return fn.call(this, args.concat([].slice.call(arguments))); }; } I always thought this was the correct way fo ...

issue with jquery fade toggle not working properly on Bootstrap website

My website is built using Bootstrap and jQuery. I am facing an issue where the fadeToggle() function on a div element is not displaying properly - it remains hidden all the time. Can anyone provide insight into what might be causing this problem, or sugg ...

Resolved z-index problem in modal dialog box

My fixed modal has a z-index set to 100, but it seems to be positioned below an element with a z-index of 2 and a position set to relative. I'm not sure why this is happening. You can view the code in this fiddle. Any insights or assistance would be g ...

As you scroll, this smooth marquee effect gently shimmers with each movement

I've been trying out this code to create a scrolling marquee text, but the issue is that after 7000 milliseconds it starts to jitter, which doesn't make the text look good. Any suggestions on how I can fix this problem? Let me know! <script ...

Having trouble getting my AngularJS directive with a number in the name to function properly

Check out my code snippet: app.directive('3dPlansSlider', function(){ return { controller: 'projectCtrl', restrict: 'E', templateUrl: 'views/3dPlansSlider.html', link: function(scope, element, attr ...

The Weglot country selector is not properly aligned with the rest of the content and its hover

Our Woocommerce store is now multilingual thanks to the weglot plugin. In the desktop view, we have integrated the country selector next to the shopping cart. For mobile view, we placed the HTML Widget in the header with some surrounding code: <div clas ...

Basic progress bar

I'm attempting to create a basic download bar, but it's only displaying as a solid color without any transition animation. Furthermore, the "repeating-linear-gradient" feature isn't functioning and I'm struggling to figure out why. I&a ...

How come HTML components are able to immediately access the updated value of useState, even though it operates asynchronously?

Why does useState update immediately inside HTML codes but only on the next render in functions? import { useState } from 'react' function uniqueFunction() { const [data, setData] = useState('previous') function submit(e) { <-- ...

Encountering net::ERR_SSL_PROTOCOL_ERROR while trying to access the Nextjs dev server using an IP address

Upon running my Nextjs project with npm run dev, I encountered an issue while accessing the app via http://localhost:3000. The resources were loaded using the HTTP protocol, such as http://localhost:3000/js/dmak_normal.js. However, when attempting to acce ...

Populate a MySql database with 2 input values

I am facing an issue with inserting values into MySql from a table. When trying to insert two values, only one gets stored in the database and the other remains empty. Here is the structure of my MySql table: https://i.sstatic.net/yWLbO.png Below is the ...

The content inside the inner div does not stretch to match the height of its parent element

I want to address a specific issue I am facing with my div structure. Although it may seem similar to other questions on StackOverflow, none of the existing solutions have worked for me. The problem is that I have two child divs inside a parent div. The h ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

How can I close the menu when a menu item is clicked in a React.js application?

I am facing an issue where I want to close the menu when clicking on any menu item in React JS. The functionality works fine with a button icon but not with individual menu items. How can I resolve this problem? I have been trying to implement it using CSS ...

Finding and Selecting Dynamic CSS Elements with CSS Selector Techniques

Utilizing a tool called Stonly for adding tooltips, the CSS Selector is used to locate the HTML element for identifying the tooltip. Depending on the user input, a dynamic task list is generated. The challenge arises when trying to pinpoint a specific task ...

Utilizing a child component in React to trigger a function on its sibling component

Trying to put this question into words is proving to be a challenge. I am wondering in React, if there is a way for a child component that is deeply nested (2 levels deep from the parent) to trigger a function on another component that it has a sibling rel ...

Eliminate unnecessary spaces in the input field located below the provided text

In the html code, I have an input field that looks like this: https://i.sstatic.net/DsD4y.png This is the CSS for the input fields: .form-control-1 { display: block; margin: 0 auto; width: 30%; height: 50px; padding: 6px 12px; font-size: 18p ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...