admin管理员组文章数量:1426666
I am new to angular.js and I was trying to create an html list with checkboxes, so what I was trying to achieve was to call a javascript function, when a user checks a checkbox.
<input id='box' ng-model='" + key + "' ng-change='graphquery(\"" + key + "\")' class = 'queryNameList css-checkbox' type = 'checkbox' />
So here, I have used ng-change
which basically captures all changes, it calls function graphquery
on both cases ( checking and unchecking)
Is it possible to specify, condition, like it should only call this function if the checkbox is checked.
I am new to angular.js and I was trying to create an html list with checkboxes, so what I was trying to achieve was to call a javascript function, when a user checks a checkbox.
<input id='box' ng-model='" + key + "' ng-change='graphquery(\"" + key + "\")' class = 'queryNameList css-checkbox' type = 'checkbox' />
So here, I have used ng-change
which basically captures all changes, it calls function graphquery
on both cases ( checking and unchecking)
Is it possible to specify, condition, like it should only call this function if the checkbox is checked.
Share Improve this question asked Jan 12, 2014 at 10:29 user1371896user1371896 2,2507 gold badges26 silver badges32 bronze badges4 Answers
Reset to default 5ng-change="!key || graphQuery(key)"
If the checkbox is checked then !key
resolves to false
, so graphQuery(key)
is executed.
If the checkbox is unchecked then !key
resolves to true
, so anything after ||
is ignored;
$scope.graphquery = function(key){
if(!$scope[key]){
//do nothing
return;
}
//do something
}
Check this example from the documentation.
ngModel on a checkbox seems to either be true
or false
and that's what gets passed to the function that you specify in ngChange
. If you want to specify a truth value or a falseness value, you can use the ngTrueValue
and ngFlaseValue
directives.
See this Plunk.
var app = angular.module('plunker', []);
app.controller('MainCtrl',
function($scope) {
$scope.graphQuery = function(key) {
if (key)
$scope.key = key
}
$scope.returnKey = function() {
return '123'
}
}
)
And in HTML
<body ng-controller="MainCtrl">
<input id='box' ng-model='key' ng-change='graphQuery()' class='queryNameList css-checkbox'
type='checkbox' ng-true-value="{{returnKey()}}" />
<pre>Key: {{key}}</pre>
</body>
So, what you want to do is check if the value of key
is true
or false
and only execute your code when the value is true
and you can specify a function in ng-true-value
to return a string in case of true
.
document.getElementById('box').addEventListener('change', function(){
if(this.checked === true) runMyFunction();
});
本文标签: javascriptCall function only when check box is checkedStack Overflow
版权声明:本文标题:javascript - Call function only when check box is checked - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745473232a2659844.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论