yavg
yavg

Reputation: 3051

Change the value of input text with the same name in Angular.js

I want it when I click on a text field, its value is changed by 2.

<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>
<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>
<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>
<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>

$scope.changeval=function(){
  //set value of input text for 2    
}

http://fiddle.jshell.net/0w36h8zm/

Upvotes: 1

Views: 306

Answers (2)

devadrion
devadrion

Reputation: 216

Use Array and Index as parameter if you have a lot of fields

<input type='text' name='field[]' ng-model='field[0]' ng-click='changeval(0)'>
<input type='text' name='field[]' ng-model='field[1]' ng-click='changeval(1)'>
<input type='text' name='field[]' ng-model='field[2]' ng-click='changeval(2)'>
<input type='text' name='field[]' ng-model='field[3]' ng-click='changeval(3)'>

js

angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {

    $scope.field = [];
        $scope.changeval=function(index){
        //change the val for 2;
      $scope.field[index]=2;
    };


});

http://fiddle.jshell.net/0w36h8zm/9/

Upvotes: 1

Adds
Adds

Reputation: 631

If you want to change the Value in all the Text fields do this:

angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {
    $scope.changeval=function(){
    $scope.field=2;
}

});

If you want to change the value of the text field on which you click then do this :

     <input type='text' name='field[]' ng-model='field1' ng-click='changeval1()'>
      <input type='text' name='field[]' ng-model='field2' ng-click='changeval2()'>
           <input type='text' name='field[]' ng-model='field3' ng-click='changeval3()'>
                <input type='text' name='field[]' ng-model='field4' ng-click='changeval4()'>




     angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {
$scope.changeval1=function(){
$scope.field1=2;
 }

$scope.changeval2=function(){
$scope.field2=2;
}

$scope.changeval3=function(){
$scope.field3=2;
}


$scope.changeval4=function(){
$scope.field4=2;
}
 });

http://fiddle.jshell.net/0w36h8zm/3/

Upvotes: 0

Related Questions