Exploring JSON data with AJAX

After successfully capturing the value and event for searching inside a json file, I encountered an unexpected issue during iteration. How can I properly select an object based on this search query? The problem arises when using .each method to loop through all records, even those that are not found.

$( document ).on('turbolinks:load', common_events)

function common_events(){
    $('.rut-input').on('change', function(event){
        $rut = $(this).val();
        var searchField = $rut;
        var expression = new RegExp(searchField, "i");
        event.preventDefault();
        $.ajax({
            type: "GET",
            url: '/companies/',
            dataType: 'JSON',
            success: function(companies){
                $.each(companies, function(i, company) {
                    if (company.rut.search(expression) > -1){
                        console.log(company.id);

                        $('.name-input').empty();
                        $('.name-input').val(company.name);
                        $('.name-input').addClass('disabled-input');
                        $('.form-group').removeClass('hide');
                        console.log(company.address);
                        if (company.address == null ){
                            $('.address-input').removeClass('disabled-input');
                        };
                    }
                    else {
                        console.log('no encuentra');
                        console.log(company);
                        $('.form-group').removeClass('hide');
                        $('.form-control').removeClass('disabled-input');
                    };
                });
            },
            error: function(companies){
                console.log('A ocurrido un error')
            },
        });
    });
}

Executing the event triggers both the if and else blocks simultaneously.

Answer №1

It appears that your intention is not to iterate through the companies array using each. Rather, you seem interested in locating a specific company and performing actions based on its details.

success: function(companies){
    const company = companies.find(c => c.rut.search(expression) > -1);
    
    if (company) {
        console.log(company.id);

        $('.name-input').empty();
        $('.name-input').val(company.name);
        $('.name-input').addClass('disabled-input');
        $('.form-group').removeClass('hide');
        console.log(company.address);
        if (company.address == null ){
            $('.address-input').removeClass('disabled-input');
        }
    } else {
        console.log('not found');
        console.log(company);
        $('.form-group').removeClass('hide');
        $('.form-control').removeClass('disabled-input');
    }
},

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

Encountering an unexpected or invalid token in line 1 after reinstallation of Windows can be a frustrating experience

Yesterday, my JavaScript file was running smoothly. However, after reinstalling Windows and Node, I'm encountering an error when trying to run the same JavaScript file today. $ node index.js C:\Users\<user-name>\Google Drive&bsol ...

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

Issue with JavaScript's replace function caused by a string syntax error

When attempting to pass an email address as a query string, I encode it just before sending it using the following line of code: var encoded = encodeURIComponent(email).replace('.', '%2E'); Even though periods should not matter in thi ...

Unlocking the power of dynamic stacking and unstacking in bar charts using chart.js

Looking to customize a barchart to toggle between stacked bars and bars behind each other? Keep in mind that the x-axes should be stacked behind each other. useEffect(() => { if (!myChart) return; if (barStack) { ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

The execution of the Javascript function is not being carried out

Why is alert("Test1") being executed, but alert("Test2") is not running? P.S. I'm currently not utilizing JSON data. <script> $(document).ready(function() { var param = 10; $.getJSON( 'modules/mod_sche ...

Manipulate the text within a swf file using jQuery

Looking for a solution to target links inside a SWF file connected to XML without access to the .fla or .swf files. Is there a way to achieve this using jQuery or Javascript? Any help is appreciated. ...

What is the process for manually testing a TypeScript function within a React application?

Hey there, I have a question as a beginner. I am currently using React and TypeScript with create-react-app, and I have some JavaScript code that is not related to the user interface (it's a module for working with a REST API). Here is an example of w ...

What steps should I take to ensure my clock stays in sync with my runTime function?

I am developing a mini digital clock project with the ability to mimic a physical clock. The clock is activated by using a power button to switch it on and display the current time. It should also be able to turn off and show an empty screen. However, th ...

Extra spaces within the source code visible after the page has been processed by Angular

Within my angular application, I am retrieving a list of addresses from a service that provides an object structured like this: { Flat: "10B", BuildingName: "Some Building", Line: "10B Some Building Road Town POST CODE", Postcode: "POST CODE", ...

Sending information from an AngularJS selected item to an edit form

Currently, I am working on an add/edit form using angularJS. Within this project, there are two templates - one for displaying a list of items and another for the form itself. While adding new items works smoothly, I have encountered some challenges when i ...

Is there a method to save the req object from a callback route to a file using NodeJS?

I have a requirement to save my req/res object to a file for future reference when redirecting to a specific page. Here is what I attempted: app.get("/route", function(req, res) { res.render("route"); fs.writeFile('./data.json', JSON.stringify ...

Incorporating ajax and jquery into html: Step-by-step guide

Previously, I inquired about implementing a show/hide functionality for a div that only renders when a specific link is clicked. (View the original question) Following some advice, I was provided with jQuery and AJAX code to achieve this: function unhide() ...

How to make a node_module global with the power of Webpack 2

I'm currently utilizing a package in an Angular project that can be found at the following link: https://github.com/pablojim/highcharts-ng One of the requirements for this package is that highcharts needs to be included as a global dependency by add ...

Is there a way to convert NuGet.NuGetVersion to a class in C# through deserialization?

As a novice programmer working on an application for my job, I recently encountered an issue while trying to deserialize a class. The class in question is named Nuget, and its structure is as follows: public class Nuget { public string? Name { get; set ...

Challenges encountered when attempting to retrieve browser information using the window.navigator object from website visitors

I've been attempting to retrieve information about the visitors' browser on my website. Unfortunately, the return I receive for each parameter is showing as 'undefined.' Below is the code I'm using (this is linked as an external J ...

A guide on handling POST response body parsing in NodeJS

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/index.html"); }); app.post("/", function(r ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Ways to access an element in a Java ArrayList with two dimensions?

I recently converted a JSON string into a Java ArrayList and now I'm trying to retrieve a specific element from it. However, using .get(0).get(2) as an example doesn't seem to provide the desired result, as I discovered in another query. Upon u ...

Vuejs method to showcase input fields based on form names

I am working on a Vue.js form component with multiple input fields, but now I need to split it into two separate forms that will collect different user input. Form 1 includes: Name Surname Email with a form name attribute value of form_1 Form 2 i ...