Blaze
Blaze

Reputation: 2329

Trigger a button whenever a button is entered on a textarea

This is a textarea element

<textarea id="textfield" paceholder="type anything here"></textarea>

This is a button

<button type="button" class="btn btn-danger" id="button">Alert</button>

I can trigger the button above to alert the value of a textarea using jquery

<script>
$(function() {
  $('#button').click(function() {
    var value = $('#textfield').val();
      alert(value);
  });
});
</script>

Is there a way I can use angular to trigger the button alert by default whenever a text or value enters into the textarea I am trying to use something like this

$scope.$watch('textfield', function () {
//pop alert if textarea has a value

but somehow lost along the line.

Upvotes: 2

Views: 74

Answers (2)

eltonkamami
eltonkamami

Reputation: 5190

You can use the built in ngKeyup directive of Angular

<div ng-app="myapp" ng-controller="myctrl">
  <textarea ng-keyup="show($event)" name="" id="" cols="30" rows="10"></textarea>
</div>

Your js

angular.module("myapp",[])
.controller("myctrl", function($scope){
  $scope.show = function($event){
    alert($event.target.value);
  }
})

If you need to force a button click everytime text is entered alter your show function as follows

angular.module("myapp",[])
.controller("myctrl", function($scope){
  $scope.show = function($event){
    alert($event.target.value);
    document.querySelector(".btn").click();
  }
})

note: ngKeyup fires every time that key is released, if you need to listen for each character entered in the textaread use the ngChange event

<div ng-app="myapp" ng-controller="myctrl">
  <textarea ng-change="show($event)" name="" id="" cols="30" rows="10"></textarea>
</div>

Upvotes: 2

antish Gajwani
antish Gajwani

Reputation: 70

ng-change will help:

<input type="textbox" ng-model="text" ng-change="change()"  />

In controller:

$scope.change = function() {
    alert($scope.text);
};

Upvotes: 0

Related Questions