Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - 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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...