Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs. Is it possible to deselect HTML “radio” input by click?

I have radio inputs and want to ucheck state by click on radio if current radio is checked.

This code:

<input type="radio" id="average_0" name="average" ng-model="checked" ng-change="false" value="500" class="ng-valid ng-dirty">
<input type="radio" id="average_1" name="average" ng-model="checked" ng-change="false" value="1000" class="ng-valid ng-dirty">
<input type="radio" id="average_2" name="average" ng-model="checked" ng-change="false" value="1500" class="ng-valid ng-dirty">

Not working.

Fiddle: http://jsfiddle.net/Zoomer/8s4m2e5e/

like image 280
user3843670 Avatar asked Aug 22 '14 08:08

user3843670


People also ask

How do I deselect a radio button in HTML?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true . When set to true , the radio button becomes checked and all other radio buttons with the same name attribute become unchecked. Here is the HTML for the examples in this article.

Can We deselect the radio button?

It is not a mandatory field. Radio button helps in ensuring only one option is selected. However, it doesn't allow user to deselect the option.


1 Answers

Radio buttons can be selected only one at a time and cannot be unchecked by the user once they are checked (unless you do programmatically). So if you want to uncheck it when it is currently selected, you can do this:

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

In your controller:

$scope.uncheck = function (event) {
    if ($scope.checked == event.target.value)
        $scope.checked = false
}

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

NOTE: If you really want to choose one or none from many options, you may opt for a <select>

like image 97
Raghavendra Avatar answered Oct 13 '22 10:10

Raghavendra