Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if checkbox is checked or unchecked in Angular.js ng-change event

I want to detect if a checkbox has been checked or unchecked when a click is happening on the checkbox.

This is what I have:

<input type="checkbox" ng-model="answers[item.questID]" ng-change="stateChanged()" />

And then in the controller I have:

$scope.stateChanged = function () {
    alert('test');
}

I'm able to fire the alert when I do check/uncheck but how can I detect the state of the checkbox? I did research a bit to find a similar issue but I wasn't able to get what I need.

like image 667
Laziale Avatar asked Dec 10 '14 22:12

Laziale


People also ask

How do you check if a checkbox is checked or not in angular?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false.

What is a checkbox in AngularJS?

In angularjs checkboxes are the form controls which are used to handle multiple selections in a form. Generally checkboxes will return true or false based on selection status.

How to get checkbox value with reactive form in angular 11/12?

In this tutorial will guide you step by step on how to get checked checkbox value with reactive form in angular 11/12 app. And as well as, take website array variable with list of variable and display list of checkbox with website name. Then add on change event to get selected checkbox value with reactive form element in angular 11/12 app.

How to check checkbox is checked or not in nG-model?

Just define an ng-model directive in the checkbox and to find checkbox checked or not check model return value (TRUE or FALSE). If it has TRUE means checkbox is been checked.

How to capture change in checkbox using jQuery?

By using the JQuery .click () method, we can capture the change like so: $ ('#terms').click (function () { if ($ (this).is (':checked')) { alert ('It has been checked!'); } else { alert ('Our checkbox is not checked!'); } });


1 Answers

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}
like image 105
PSL Avatar answered Oct 16 '22 16:10

PSL