Using AngularJS, I would like to create a list of options with radio buttons, the last of which has an empty text field labeled \'Other\' for inputing an option that is not
I made some very small modifications to your pen HERE.
The short of it is, instead of having 'Other' as a value, i made it a blank option, with the input actually controlling the value.
$scope.colors = [
"Red",
"Green",
"Blue",
""
];
html:
<label >
{{color || 'Other'}}
</label>
<input type="text" ng-model="$parent.color" ng-show="color==''">
This allows the input to actually control the value of 'Other'...
Add a separate scope property for the other text:
$scope.other = '';
Add a colorChanged()
method which will be called when the color is changed. This will set the other text to empty if color is not 'Other':
$scope.colorChanged = function () {
if ($scope.color != 'Other') {
$scope.other = '';
}
};
This will also need to be called from changeColor()
. I ended up changing changeColor
to allow the color to be passed in. It otherwise defaults to red:
$scope.changeColor = function(color){
$scope.color = color || "Red";
$scope.colorChanged();
};
Add ng-change="colorChanged()"
to radio button:
<input type="radio" ng-model="$parent.color" ng-value="color" id="{{color}}" name="color" ng-change="colorChanged()">
Change the textbox to use other
as the model. Use ng-focus to detect when textbox is focused and then set color to 'Other'. Doing this will select the radio button.
<input type="text" ng-model="$parent.other" ng-show="color=='Other'" ng-focus="$parent.color = 'Other'"/>
Update the display of the color to show the other text:
The chosen color is <strong>{{color}}<span ng-if="color === 'Other' && other != ''"> - {{other}}</span></strong>
Plunkr