Error encountered - Unable to read the property 'map' of an undefined array

Having multiple values to send, such as those needed for customer user creation.

Here is where I found a solution: (Using an object array as input data)

I adapted the code to extract only the true knowledge values.

Upon inspecting my button, an error occurred:

Array[0]

TypeError: Cannot read property 'map' of undefined

HTML view:

<ul style="list-style-type:none;">
    <li class="col-md-4" ng-repeat="Value in ColorAddUppers">
        <img ng-src="{{Value.Image}}" class="img-responsive img-rounded mb-lg" />
        <p class="label label-lg label-primary full-width">
            <input type="checkbox"
                    ng-model="Value.selected"
                    name="selectedColorUppers[]"
                    value="{{Value.IDColor}}" />
            {{Value.Text}}
        </p>
    </li>
</ul>

CreateUser.js

var url = "/JsonClass/ColorAddToUppers";
$http.get(url).success(function (response) {
    $scope.ColorAddUppers = response;
});


//Overdel
$scope.NextLvlThree = function () {
    //Check Color Values

    $scope.selectionColorUppersView = [];
    $scope.selectedColorUppers = function selectedColorUppers() {
        return filterFilter($scope.ColorAddUppers, { selected: true });
    };
    $scope.$watch('fruits|filter:{selected:true}', function (nv) {
        $scope.selectionColorUppersView = nv.map(function (ColorNameUppersText) {
            return ColorNameUppersText.Text;
        });
    }, true);

    console.log($scope.selectionColorUppersView);
}

EDIT (Update)

enter image description here

After examining this image, it seems that the values are not being retrieved.

In my code, I have utilized the following method:

$scope.selectedTextValuesByWatch = [];

    $scope.$watchCollection('ColorAddUppers|filter:{selected:true}', function (nv, ov) {
        $scope.selectedTextValuesByWatch = nv.filter(function (value) {
            return value.selected;
        }).map(function (value) {
            return value.Text;
        });
    }, true);

    $scope.getSelectedTextValues = function () {
        return $scope.ColorAddUppers.filter(function (value) {
            return value.selected;
        }).map(function (value) {
            return value.Text;
        });
    }

    console.log($scope.selectedTextValuesByWatch);

    if($scope.selectedTextValuesByWatch.length >= 1)
    {
        console.log("check");
    }
    else
    {
        console.log("error");
    }

Answer №1

When calling the NextLvlThree() function, it's important to note that the declaration of the $watch should be at the controller level rather than inside the function to prevent multiple declarations.

There are various methods to retrieve selected values in a list:

One way is to use a dynamic filter in the view, which can display select values as JSON:

<pre>{ColorAddUppers|filter:{selected:true}|json}}</pre>

Another approach is to implement a watch that updates the selected list with only the Text of each value:

$scope.$watchCollection('ColorAddUppers|filter:{selected:true}', function (nv, ov) {
   $scope.selectedTextValuesByWatch = nv.filter(function (value) {
      return value.selected;
   }).map(function(value) {
      return value.Text;
   });
}, true);

Alternatively, you can create a function that performs the same filtering as the watch but is triggered when the user clicks on a button:

$scope.getSelectedTextValues = function() {
    return $scope.ColorAddUppers.filter(function(value) {
       return value.selected;
    }).map(function(value) {
       return value.Text;
    });
}

You can see all three approaches in action by checking out this plunker 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

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

split the string into multiple instances

I have a string that I need to manipulate; $string = '[PAGE][TITLE]Navigation Link 1[TITLE]Content Here[PAGE]'; and I want the output to be like this; <div id="navigation Link 1">Content Here</div> I tried using this code ...

Ensuring Data Integrity with JavaScript Form Validation

Ensure that if text box A is filled in, text box B must also be filled in before submitting. Vice versa, if text box B is filled in, make sure text box A has data as well. Is it possible to loop this check for multiple text boxes? For example, if row A o ...

Identifying the device name in Safari on iOS 13 despite the inaccurate display of the user agent - a step-by-step guide

Following the release of Apple's iOS 13, I discovered that window.navigator.userAgent in Safari on iPad iOS 13 is identical to that on MacOS. It appears like this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) ...

Display <tr> tag when button is clicked without refreshing the page

I have a specific requirement to hide a certain tag initially. If the user clicks the forward button without selecting any radio buttons or checkboxes, the tag should be displayed and the page should not refresh. However, there seems to be an issue with ...

Limit input to numbers only in Semantic UI React Form Field

I've developed a custom CurrencyInput React component for users to input numeric values. I set the input type to "number", but unfortunately, this only seems to function properly in Chrome (as Firefox still allows non-numeric entries). Here is the co ...

Arranging Array of Date Strings in Ascending and Descending Sequences

Check out the code below: var dateArr = new Array(); dateArr[0] = "11-12-2012"; dateArr[1] = "9-12-2014"; dateArr[2] = "11-12-2012"; dateArr[3] = "9-12-2011"; Looking for suggestions and examples on how to sort the String Date array above in ascending an ...

Animate the page transition with jQuery once the CSS animation finishes

My screen is split in two halves, and when you click on a side, they are supposed to slide open like curtains and then fade into another page. I have successfully created the animation using CSS and jQuery to add the appropriate class on the click event. ...

Python coding for nested lists is an innovative way to organize data

Suppose we have a list of integers A=[1,2,3,4,5,6,7,9] and another list p=[4,5,9]. How can we divide the values in A so that those not present in p are grouped into sub-lists based on the position of the elements from p within A? For instance, for the give ...

The integration of Tailwind merge is experiencing issues when used with CSS modules

My Next.js project utilizes Tailwind for styling elements, and I rely on Tailwind's merge feature to address class precedence issues within my components. It appears that the merge feature does not function correctly when working with CSS modules (spe ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

Meteor: Uncaught ReferenceError: require is undefined

After installing meteorhacks:npm and defining apn in packages.json as {"apn": "1.6.2"}, I encountered an error message stating ReferenceError: require is not defined when trying to execute the following code: var apn = Npm.require('apn'), pa ...

What could be causing my Java "for" loop to suddenly terminate?

After successfully building the array in my initial loop, I encountered a problem when attempting to print out the results in the second "for" loop as it abruptly terminates. Despite thorough inspection, I cannot seem to find the error in my code. Here i ...

How to successfully transfer input data from a dialog to a controller using jQuery and Grails

As a newcomer to Grails and jQuery, I recently created a jQuery dialog following this example: http://jqueryui.com/dialog/#modal-form The goal is to open a dialog, input data, and have it displayed in a dynamic table on the main page. Once all entries are ...

Submitting an array from jQuery to Django

I'm having trouble sending a jQuery array of simple numbers to Django via POST, and I can't seem to figure out what's going wrong. Any assistance would be greatly appreciated. Currently, I'm encountering an Http 500 error with the messa ...

Is it possible for an Ajax/jQuery script to display multiple dependent dropdown box options within a single Form URL?

In the process of developing a basic form prototype that includes 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Depen ...

Tips for organizing classes in a Node module

Is it recommended to organize classes in a node module using the following method, or is there a more efficient way to achieve this? // mymodule/core.js module.exports = { ClassA: require('./class/ClassA'), ClassB: require('./class ...

What is the best way to organize arrays that are pointed to by an array of pointers

Is there a more effective way to sort arrays pointed by an array of pointers with the getSort function? void getSort(int** p2a, int arrSizes[]) //p2a is an array of pointers to different arrays An attempt was made using bubble sort: if (i < 5) { ...

Failure to trigger the callback for mongoose.connection.once('open') event

Currently, I am in the process of setting up a custom Node server using Next.js. Although I'm utilizing Next.js this time around, it should not affect the outcome. In my previous applications, I always relied on mongoose.connection.once('open&ap ...

The server encountered a 405 error due to its inability to redirect to the specified URL

Hi there! I'm currently in the process of developing a payment page using WebAPI2 and AngularJS. Within my payment API, there is a field called "redirecturl" which is used to redirect users to a specific page once the payment is successful. I've ...