0

Is there a way I can deselect a radio button on click of it? I'm using AngularJS 1.4.4. Using one of the solutions I found here, I've added an ng-click event, but it doesn't work.

foreach (var part in Model.ChildParts)
 {
  <div class="radio  col-md-12">
    <input type="radio"
           id="@Model.FieldName"
           name="@Model.FieldName"
           ng-model="gPA(@Model.Id).value"
           value="@((part as BaseInputPartVM).GetStringValue())"
           ng-click="uncheck($event, @Model.Id)" />
  </div>
 }

In the controller, I have the following code. The below "if" condition is always turning to true and hence everytime I try selecting a radio, it is always set to false. My goal is to deselect a radio button on click of it, if it is already selected.

$scope.uncheck = function (event, partId) {
      if ($scope.gPA(partId).value == event.target.value)
         $scope.gPA(partId).value = false
}
Test_User
  • 171
  • 1
  • 6
  • 16
  • try changing `value` to `ng-value` – Pankaj Parkar Oct 22 '15 at 17:56
  • Yes try using ng-value and setting that true or false, see http://stackoverflow.com/questions/14530785/angularjs-how-to-set-radio-button-checked-based-on-model – Daniel Kobe Oct 22 '15 at 18:05
  • In the input element, I've changed value to ng-value. Still the issue persists. I'm able to deselect the radio button, however it doesn't allow me to select the radio buttons. Same is the case with my original code that I posted above. – Test_User Oct 22 '15 at 18:26

2 Answers2

0

The radio button, by design, is not supposed to be unselected. I would consider using a checkbox instead. https://ux.stackexchange.com/questions/13511/why-is-it-impossible-to-deselect-html-radio-inputs

Community
  • 1
  • 1
Ben
  • 209
  • 2
  • 8
0

Following code worked:

foreach (var part in Model.ChildParts)
{
  <div class="radio  col-md-12">
    <input type="radio"
           id="@Model.FieldName"
           name="@Model.FieldName"
           ng-model="gPA(@Model.Id).value"
           value="@((part as BaseInputPartVM).GetStringValue())"
           ng-mouseup = "setPreviousSelectedValue(@Model.Id)"
           ng-click="uncheck($event, @Model.Id)" />
  </div>
}
<input type="hidden" id="previousRadioSelection" name="previousRadioSelection" ng-model="previousRadioSelection" value="" />

In the controller,

//set previous selected value of radio button      
$scope.setPreviousSelectedValue = function (partId) {
    $scope.previousRadioSelection = $scope.gPA(partId).value;
}

//uncheck radio button      
$scope.uncheck = function (event, partId) {
    if ($scope.previousRadioSelection == event.target.value)
        $scope.gPA(partId).value = null;
}
Test_User
  • 171
  • 1
  • 6
  • 16