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
}
3
  • try changing value to ng-value Commented Oct 22, 2015 at 17:56
  • Yes try using ng-value and setting that true or false, see stackoverflow.com/questions/14530785/… Commented Oct 22, 2015 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. Commented Oct 22, 2015 at 18:26

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.