Validating in Angular cannot be accomplished

I am facing an issue with validating my input against JSON data. Every time I try to compare it with the JSON, only the else block gets executed. Can someone please help me resolve this problem?

<body ng-app="fileGetting" ng-controller="loadFile">
    <label>Firstname:</label><input type="text" ng-model="placeFile.fname"><br>
    <label>Lastname:</label><input type="text"  ng-model="placeFile.lname"><br>
    <button ng-click="fun()">Submit</button><br>
    <div ng-repeat="x in placeFile">
        <p>{{x.fname}}</p>
    </div>  
    <script>
        angular.module("fileGetting", [])
        .controller("loadFile", function($scope, $http) {
            $http.get("exam.json").then(function(response) {
                $scope.placeFile = response.data.names;
                var x = $scope.placeFile;
                $scope.fun = function() {
                    angular.forEach(x, function(value, key) {
                        if ($scope.placeFile.fname == x.key && $scope.placeFile.lname == x.key)
                        {
                            alert("hi ram");
                        }
                        else
                        {
                            alert("this is incorrect");
                        }
                    });
                }
            });
        });
    </script>

Below is the JSON data being used:

{
    "names":[
              {
                "fname":"Ram",
                "lname":"Chandru"
              },

              {
                "fname":"Chandran",
                "lname":"Krishna"
            },

            {
                "fname":"Jayanth",
                "lname":"Jo"
            }
        ]
    }

Answer №1

After much anticipation, I finally received a response that I am grateful for from Magnus and Simon.

<body ng-app="myApp" ng-controller="loadFile">
<label>Firstname:</label><input type="text" ng-model="current.fname"><br>
   <label>Lastname:</label><input type="text"  ng-model="current.lname"><br>
   <button ng-click="fun()">Submit</button><br>

   <script>
  angular.module("myApp", [])
        .controller("loadFile", function($scope, $http) {

        $scope.current = {fname:"", lname:""};
           $http.get("exam.json").then(function(response) {
                $scope.placeFile = response.data.names;
                $scope.fun=function(){
                    $scope.placeFile.forEach(function(itm) {
                        if ($scope.current.fname===itm.fname && $scope.current.lname === itm.lname ) {
                            alert("Hi Ram");
                        }

                        });
                }
        });
        });
      </script>  

Answer №2

If I have grasped your intentions correctly, the following steps should resolve your issue:

Start by modifying

   <label>Firstname:</label><input type="text" ng-model="placeFile.fname"><br>
   <label>Lastname:</label><input type="text"  ng-model="placeFile.lname"><br>

to

<label>Firstname:</label><input type="text" ng-model="current.fname"><br>
   <label>Lastname:</label><input type="text"  ng-model="current.lname"><br>

The updated code snippet should be as follows:

angular.module("myApp", [])
      .controller("loadFile", function ($scope, $http) {
          $scope.current = { "fname": "", "lname": "" };
          $scope.placefile = [];
          $http.get("exam.json").then(function (response) {
              $scope.placeFile = response.data.names;
          });
          $scope.fun = function () {
              $scope.placeFile.forEach(function (itm) {
                  if (itm.fname ===  $scope.current.fname 
                  && itm.lname === $scope.current.lname) {
                      alert("Hi Ram");
                  }
                  else {
                      alert("incorrect");
                  }
             });

                };
        });

Best Regards

Magnus

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

Issue: { error: 'Unrecognized interaction', error code: 10062} in discord.js version 14

Every command runs perfectly fine except for /rank, which triggers the "Unknown interaction" error. This only happens when there are no issues with error handling, such as providing a valid user id and rank id. When there are problems, it works fine. I pr ...

Unusual border effect on three.js webgl transparent png texture

Currently facing an unusual issue with using pngs as textures in three.js. The pngs develop odd borders at the transition between visible and transparent areas. I have tried adjusting the alphatest value, but this sometimes causes the image to disappear ...

Exploring the Fusion of Data in VueJS

Trying to figure out how to merge data from two different sources to display in a single table. One source is created within my Vue instance, while the other is imported from an API. Any suggestions on how to achieve this? HTML: <div class="ui conta ...

Tips for modifying a state array in Vuex

I have the ability to add and remove entries, but I'm struggling with editing. How can I achieve this using VUEJS, VUEX, and JavaScript? For adding entries, I know I should use PUSH, and for removing entries, SPLICE works fine. But what about editing ...

The function grunt.task.run() is malfunctioning

Currently, I am experimenting with integrating Grunt into my Express application. Here is a snippet of the code I have: var grunt = require('grunt'); require(process.cwd() + '/gruntfile.js')(grunt); grunt.task.run('development&ap ...

Ruby on Rails JSON API - flawless JSON without any errors

When I am displaying an array of ActiveRecord items, each has been processed through the valid? method so errors are already defined. The rendering of the array is done as follows: render json: array_of_objects I have ActiveModelSerializers.confi ...

Assign a value to an Html.HiddenField without tying it to the model upon form submission

I have two classes, SubsidiaryClient and Client, that are related in a one-to-many manner as depicted below. Currently, I am utilizing MVC 5 for development. In the Create SubsidiaryClient page, to retrieve the ClientID, you need to click on the browse bu ...

Utilizing Javascript to Parse Json Information

For my latest project, I am attempting to retrieve JSON data from a specific URL and display it on a web page using only JavaScript. This is all new to me. Can someone assist me in fetching the JSON data from the following link: I have been experimenting ...

Tips for sending icons as properties in React using TypeScript

Recently diving into typescript, I embarked on a straightforward project. Within this project lies a sidebar component that comprises multiple sidebarNavigationItem components. Each of these Sidebar items consists of an Icon and Title, showcased below. Si ...

The data displayed in the <span> element isn't reflecting the response from the loaded page, despite being visible in Firebug

I have encountered a problem while trying to load a signup.php page into a div on my main page. All the elements (forms, JavaScript, etc.) function correctly in the loaded page, except for one issue - I cannot get the response from the PHP script to displa ...

Guide on centering an element on a screen using Selenium and Python

I am currently working on automating a webpage with Robot Framework, Selenium, and Python. As part of the automation process, I need to scroll an element to the middle of the screen before clicking on it. Although I have tried using the following code: se ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

What is the best way to assign multiple values to certain elements within an array?

I have an array that looks like this: items = { item1: 10, item2: 5, item3: 7, item4: 3, }; I am looking to include additional details in this array, for example: items = { item1: 10 {available: true}, ...

Tips on how to retrieve the value of the second td in an HTML table when clicking on the first td utilizing jQuery

There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery. $('.tbody').on('click','tr td:nth-child(1) ...

Tips for fixing prettier errors in express and TypeScript code

I have set up a simple Node/Express + Typescript application app.listen(PORT, (): void => { console.log(`app is running in ${environment} and listening on port ${PORT}!`); }); I am encountering an error and I am unsure of the cause? Replace PORT, wit ...

Having trouble with your contact form and not getting it to work properly with Javascript, Ajax, or

I've been struggling to get a contact form working for an entire day. I included the following script at the top of my page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> This is the structure ...

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...

What is the best way to apply a class to an element in an input template using Angular's ngFocus directive, or any directive incorporated in the Ionic Framework?

I'm working with a template that looks like this: <label class="item item-input" ng-class="{'focus':authData.username.focus}"> <--add class here if input:focus <span class="input-label">Username</spa ...

Android JSON to POJO deserializer with support for polymorphic classes

I'm facing an issue with REST and Android. The problem arises when working with a transport object within the context of a Human class that has Male and Female subclasses. My goal is to use JSON as the transport medium for the human object. Typically, ...