How to deselect a radio button in AngularJS

I have explored various solutions using ng-dblclick, $event, etc, but none of them seem to work for me.

Within a table, I have two radio buttons inside an ng-repeat. I have a field that determines which radio button should be active. While using ng-change works well for this purpose, I also want to be able to deselect any of the radio buttons. However, ng-change does not trigger in this case, so I added ng-click as well. The code below is functional, but I am curious if there is a cleaner way to achieve this.

<td>
    <div class="inline-group">
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-change="save(item, false)" ng-click="save(item, true)" ng-model="item.Stage" value="Started">
            <i></i> Started
        </label>
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-change="save(item, false)" ng-click="save(item, true)" ng-model="item.Stage" value="Completed">
            <i></i> Completed
        </label>
    </div>
</td>

Controller

var runOnce = false;

$scope.save = function (item, uncheck) {
    if (runOnce) {
        return;
    }

    if (uncheck) {
        item.stage = null;
    }
    else {
        runOnce = true;
    }

    ...
    .$promise.then(function (result) {
        ...
        runOnce = false;
        ...
     });
    ...

Answer №1

Radio buttons allow only one selection at a time and cannot be deselected by the user once chosen, unless changed programmatically. Here is a cleaner example:

<input type="radio" ng-model="selected" value="500" ng-click="deselect($event)" />
<input type="radio" ng-model="selected" value="1000" ng-click="deselect($event)" />
<input type="radio" ng-model="selected" value="1500" ng-click="deselect($event)" />

In your controller:

$scope.deselect = function (event) {
    if ($scope.selected == event.target.value)
        $scope.selected = false
}

DEMO: http://jsfiddle.net/8s4m2e5e/3/

Answer №2

For detailed information, please refer to the official documentation

<div class="inline-group">
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="true">
            <i></i> Initiated
        </label>
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="false">
            <i></i> Finished
        </label>
    </div>

For a binary choice, consider utilizing a checkbox instead of a radio button

Latest Version

Directly declare an enum in your scope:

$scope.stageEnum = { Initiated: 0, Finished: 1 };

Template :

<div class="inline-group">
            <label class="radio">
                <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="stageEnum.Initiated">
                <i></i> Initiated
            </label>
            <label class="radio">
                <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="stageEnum.Finished">
                <i></i> Finished
            </label>
        </div>

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

Is it possible to delete and substitute all content following a specific DIV tag?

Is there a way to utilize JavaScript or jQuery to remove all content following a specific div element and insert new code? The div elements are generated dynamically, and I need to remove everything after the last div that looks similar to: & ...

Does PHP/AJAX only function when an output is generated?

I am attempting to fetch the Wordpress blog header into a php file in order to use it for an AJAX call function. define('WP_USE_THEMES',false); echo 'Something'; require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-b ...

A Vue element that has multiple exact click handlers will consistently trigger the click.exact method when clicked with system modifiers

According to the information found at https://v2.vuejs.org/v2/guide/events.html#exact-Modifier, I am attempting to build an element that triggers different methods based on additional keys pressed at the time of clicking. <span @click.exact="method ...

What is the process for displaying information from a database on a model popup box?

I am working on displaying books in the Index view that are retrieved from a database. Each book has a button underneath it. The goal is to have a modal box appear when these buttons are clicked, showing details of the corresponding book such as the book i ...

"The issue I'm facing with Next.js is that the fetched data is not displaying in the template. Additionally, I'm

I am encountering an issue with my API data where it is being called twice in the terminal. Additionally, I am trying to display this data on my page template but for some reason, it is not showing up. Here is the code snippet in question: Here is my code ...

Integrate PHP include files into a website without allowing direct access, then dynamically load them using jQuery AJAX

I am utilizing jQuery AJAX to load the content of about.php page into my index.php section in this manner: $('.nav a[href="#about"]').on('click', function() { $('main').load('../../layout/about.php'); }); The iss ...

Is there a way to assign a value of 1 to the input-group spinner?

At first, I thought this problem would be easy to solve, but now I'm finding myself stuck. My goal is to have the input-group spinner display the value 1 when a user opens the application. <input id="option1" type="number" min="1" value ="1" ...

Tips for correctly implementing JavaScript conditional statements

Upon running this jQuery (1.8.3) code, I consistently receive the "in" alert message even when the length is greater than 1. The purpose of my actions is to dynamically add elements to a menu while ensuring that the element does not already exist. Even a ...

Exploring the concept of passing 'this' as a parameter in JavaScript

<button type="button" aria-haspopup="dialog" aria-controls="b" onclick="openLayer($('#b'))"> button</button> <div role="dialog" id="b"><"button type="button">close<"/button></div> function openLayer(target){ ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Unable to bypass YouTube advertisement

I am currently experimenting with using nodejs puppeteer to test if I can bypass the ad on Youtube. Although this is just for testing purposes, I am facing some challenges with getting it to work as expected. I have implemented a while loop to search for ...

Incorporate an external object not native to the Angular framework within a factory

We're in the midst of a debate and I'm hoping you can help us reach an agreement. Imagine I have a basic factory set up like this: angular.module('myModule', []) .factory('Fact', function() { var Fact = function() { ...

Error Alert: JQuery Pop Up Issue

Struggling with getting my JQuery Pop-Up Box to work properly. Any guidance for a newbie like me on how to fix it would be greatly appreciated. Here's the code I've been working on: <!-- POP UP HTML --> <div class="infocontainer"> ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

What steps can be taken to disable the send button once it has been used and then automatically show gratitude?

My website features a contact form, but I noticed that when users press the send button, there is no confirmation message indicating whether the message was successfully sent. This could potentially lead to multiple spam emails being sent to me. How can I ...

Steps to enable editing in an array

I'm struggling to implement an editing functionality for the lists inside the ul element in my simple to-do list project. Currently, I have the delete functionality working but need guidance on how to add an edit function. The list items are added by ...

I desire a smooth fade-in transition for the background image when the addClass function is

If the background color is set to header-fixed-position, the color will fade in. However, if the background is an image, the image will not fade in. Apologies for my lack of proficiency in English. Please refer to the sample code below. Try removing the c ...

The ForbiddenError has struck again, this time wreaking havoc in the realms of Node.js, Express.js

I am currently adapting this GitHub sample application to utilize Express instead of KOA. However, I am encountering an Access Denied issue when the / route in Express attempts to load the index.html. What specific modifications are required in the code be ...

What is causing the error in this particular stream function?

I created a function that logs the provided arguments to the console when piped into it. function logToConsole() { var stream = new Stream.Transform({objectMode: true}), args = [].slice.call(arguments); stream._transform = function (data, ...