简体   繁体   中英

How to set input field value when check box is checked using Angular.js

I need when i will be checked the check box the respective input field will have the required value. Let me show my code below.

<label class="checkbox-inline">
    <input type="checkbox" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
    <input type="checkbox" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />

I need here when user will check the Five the input field will get 5 and when user will check Ten ,the input field value will be 10 .

use ng-true-value="" in checkbox

Like this

<label class="checkbox-inline">
    <input type="checkbox" ng-model="color" ng-true-value="5" ng-false-value="0" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
    <input type="checkbox" ng-model="color" ng-true-value="10" ng-false-value="0" ng-model="color" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />

JSFIDDLE

I thought maybe you meant to use radio instead of check boxes (since the color can be either 5 OR 10). here's a working plnkr .

and the code:

<label class="checkbox-inline">
    <input type="radio" name="favoriteColors" ng-model="data.color" value="5"> Five
</label>
<label class="checkbox-inline">
    <input type="radio" name="favoriteColors" ng-model="data.color" value="10"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="data.color" readonly />

js:

app.controller('MainCtrl', function($scope) {
  $scope.data = { color: '' };
});
<label class="checkbox-inline">
    <input type="checkbox" ng-click="color=5" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
    <input type="checkbox" ng-click="color=10" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />

https://jsfiddle.net/5s1bfjco/7/

Bind your checkbox inputs to ng-model as well, and then assign the value accordingly. Something like this:

<input type="checkbox" name="favoriteColors" ng-model="isChecked.five"> Five
<input type="checkbox" name="favoriteColors" ng-model="isChecked.ten"> Ten

In your controller:

$scope.isChecked = {};
if ($scope.isChecked.five) {
  $scope.color = 5;
}
if ($scope.isChecked.ten) {
  $scope.color = 10;
}

It should automatically update your input value as you check/uncheck the checkboxes, due to two-way binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM