Counting radio buttons in AngularJS and handling undefined values when passing parameters

After spending countless hours trying to figure out how to count radio buttons, I encountered another issue where the value passed to ng-change would become "undefined". My question is, how can I successfully pass that value? Any assistance with counting only non-zero value radio buttons would be greatly appreciated.

I specifically want to count radio buttons with a value other than 0.

<!DOCTYPE html>
<html ng-app="myapp">

<head>
    <title>AngularJS</title>
    <link rel="stylesheet" href="/content/css/styles.css" type="text/css">
    <link rel="stylesheet" type="text/css" href="/content/css/font-awesome.min.css">
    <script src="/app/lib/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="/app/app.js"></script>
</head>

<body>
    <form ng-controller="MainCtrl">
        <table>
            <tr ng-repeat="item in data">
                <td>
                    <input type="radio" name={{item.name}} ng-change="updateTotal(item)" ng-model="item.value">
                    {{item.name}}
                </td>
            </tr>
        </table>
        <hr>
        <p>
            Total checked: {{totalSelected}}
        </p>
    </form>

</body>

</html>

JavaScript file:

var app = angular.module('myapp', []);

app.controller('MainCtrl', function ($scope) {

    $scope.init = function () {
        $scope.data = $scope.createData();
        $scope.totalSelected = 0;
    }

    $scope.createData = function () {
        return [{
                'name': 'cow',
                'selected': false,
                'value': 1
            },
            {
                'name': 'cow',
                'selected': false,
                'value': 2
            },
            {
                'name': 'cow',
                'selected': false,
                'value': 0
            },

            {
                'name': 'rat',
                'selected1': false,
                'value': 1
            },
            {
                'name': 'rat',
                'selected': false,
                'value': 2
            },
            {
                'name': 'rat',
                'selected': false,
                'value': 0
            },

            {
                'name': 'cat',
                'selected': "false",
                'value': 1
            },
            {
                'name': 'cat',
                'selected': "false",
                'value': "2"
            },
            {
                'name': 'cat',
                'selected': "false",
                'value': "0"
            }
        ];
    }

    $scope.updateTotal = function (item) {
        console.log(item);
        if (item) {
            $scope.totalSelected++;
        } else {
            $scope.totalSelected--;
        }
    }
    $scope.init();
});

Console log:

{name: "cat", selected: "false", value: undefined, $$hashKey: "object:10"}
{name: "cat", selected: "false", value: undefined, $$hashKey: "object:11"}

Answer №1

Utilize value="{{item.value}}" to set a value for the radio button as shown in the example below:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<form ng-controller="MainCtrl">
        <table>
            <tr ng-repeat="item in data">
                <td>
                    <input type="radio" name={{item.name}} ng-change="updateTotal(item)" ng-model="item.value" value="{{item.value}}">
                    {{item.name}}
                </td>
            </tr>
        </table>
        <hr>
        <p>
            Total selected: {{totalSelected}}
        </p>
    </form>

<script>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
    $scope.init = function () {
        $scope.data = $scope.createData();
        $scope.totalSelected = 0;
    }

    $scope.createData = function () {
        return [{
                'name': 'cow',
                'selected': false,
                'value': 1
            },
            {
                'name': 'cow',
                'selected': false,
                'value': 2
            },
            {
                'name': 'cow',
                'selected': false,
                'value': 0
            },

            {
                'name': 'rat',
                'selected1': false,
                'value': 1
            },
            {
                'name': 'rat',
                'selected': false,
                'value': 2
            },
            {
                'name': 'rat',
                'selected': false,
                'value': 0
            },

            {
                'name': 'cat',
                'selected': "false",
                'value': 1
            },
            {
                'name': 'cat',
                'selected': "false",
                'value': "2"
            },
            {
                'name': 'cat',
                'selected': "false",
                'value': "0"
            }
        ];
    }

    $scope.updateTotal = function (item) {
        console.log(item);
        if (item) {
            $scope.totalSelected++;
        } else {
            $scope.totalSelected--;
        }
    }
    $scope.init();
});
</script>

</body>
</html>

Answer №2

Experiment with ng-click to trigger a function and utilize ng-checked for the selected attribute! :)

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

Can you explain the role of [Yield, Await, In, Return] in EcmaScript syntax?

EcmaScript production rules often include the use of "modifiers" such as: [Yield, Await, In, Return] Here are a couple of examples: ArrayLiteral[Yield, Await]: ... ElementList[Yield, Await]: ... AssignmentExpression[+In, ?Yield, ?Await] I have look ...

Accessing the facebox feature within a dropdown menu

Looking for assistance in creating a function to open a facebox when an option from a drop down list is selected. Here is what I have so far: <select><option value="www.google.com/" id="xxx"></option></select> In the header sectio ...

Updating Bootstrap modal content based on button clickExplanation on how to dynamically change the content

I am looking to dynamically change the content displayed inside a modal based on the button that is clicked. For example, clicking button one will only show the div with the class 'one' while hiding the others. $('#exampleModalCenter&a ...

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

What is the best way to solve the problem of Chrome auto-complete overlapping with labels in Vuetify?

When attempting to make a login form using outlined text fields in Vutify, there is an issue with Chrome autocomplete overlapping the labels. <v-text-field v-model="email" label="e-mail" name="email" outlined prep ...

Exploring the Power of Two jQuery Ajax Functions in Your Script

Is it possible to provide guidance on how I can successfully execute two separate Ajax calls within a single script without encountering conflicts? A sample of the current script structure is as follows: <script type="text/javascript"> $(document).r ...

Tools for parsing command strings in NodeJS

Currently, I'm utilizing SailsJS for my application. Users will input commands through the front-end using NodeWebkit, which are then sent to the server via sockets. Once received, these commands are parsed in the back-end and a specific service/cont ...

Enhance npm package by implementing custom functionality with React Component

I have designed an app that bears a striking resemblance to the following code: class MyCustomApp extends React.Component { constructor (props) { super(props) this.state = { tags: [ { id: 1, name: "Oranges" }, { id: 2, ...

Fetching JSON object from a node.js/express server using AJAX request

I've implemented server-side code to fetch data from an external website and return a JSON object to the client side of my node.js/express application. The intention is to further process this JSON on the client side. Within my index.js file, I have ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

JkMegaMenu drop-down menus in Chrome are shifting to the left when the window is resized

Currently, I am utilizing the JKmegamenu plugin to incorporate a megamenu into a website that is currently under development. The megamenu functions properly and has an attractive appearance. However, there seems to be an issue where the drop-down divs shi ...

The Google Map is not showing all the details

Our app is developed using ReactJS on Rails API, with a Google map integrated. However, when visiting this link and clicking "Map View", some grey space appears under the Google Map. An example image can be found here: example We are having trouble findi ...

Creating a Recursive Facebook Page Data Scraper using Selenium and Node.js

I am trying to iterate through an array of Facebook page IDs and retrieve the code from each event page. However, I am encountering a problem where I only get the code of the last page ID in the array repeated multiple times. For example, if there are 3 ID ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

Retrieving information from a different controller

There is only one controller in my code. app.controller('first',['$scope','scopeService', function ($scope,scopeService){ $scope.initialize = function() { scopeService.store('value', $scope); } }]); The secon ...

Organizing nested files with JAWR: a systematic approach

Recently, I started using JAWR to bundle my AngularJS files. However, I encountered an issue where the files were being loaded out of order. Here is my directory structure: app app.js folderA something.controller.js something.module.js I want the f ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...