Execute the function only if the checkbox has been selected

Just starting out with angular.js and I wanted to create an html list with checkboxes. My goal was to trigger 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' />

Here, I've used the ng-change directive which captures all changes and calls the graphquery function regardless of whether the checkbox is checked or unchecked.

Is there a way to specify a condition so that the function is only called when the checkbox is checked?

Answer №1

ng-change="!selected || updateData(selected)"

When the checkbox is selected, !selected becomes false, triggering the execution of updateData(selected).

If the checkbox is deselected, !selected becomes true, causing anything after || to be disregarded;

Answer №2

$scope.dataHandler = function(data){
  if(!$scope[data]){
   //no action required
   return;
  }

//process data accordingly
}

Answer №3

Take a look at this sample from the official documentation.

When using ngModel on a checkbox, it will be either true or

false>, which is then passed to the specified function in <code>ngChange
. To define specific truth and falseness values, utilize the ngTrueValue and ngFalseValue directives.

For a live demonstration, view 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'
    }
  }
)

Below is the HTML code:

<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>

To ensure that your code only executes when the value of key is true, you can specify a custom function in ng-true-value to return a string in such cases.

Answer №4

function triggerFunction() {
  document.getElementById('box').addEventListener('change', function(){ 
    if(this.checked === true) runMyFunction();
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to create a curve that stays below the text and does not intersect with it?

I am attempting to center a text on a quadratic curve or line, as shown in the image below: https://i.stack.imgur.com/XH6Fw.png My current approach using ctx.fillText results in the text overlapping the curve. https://i.stack.imgur.com/ddwue.png Is ther ...

Error while animating with jQuery

It's the wee hours of the morning and my jQuery skills are not the greatest. Can anyone point out the silly mistake I'm making? I've created a JSFiddle for easy access: http://jsfiddle.net/JamesKyle/7GWRp/ Due to an issue with CSS transiti ...

Tips for positioning a highcharts pie chart and legend in the middle of a page

I'm struggling to center my highchart data in a node/react single page application. Currently, it appears off-center like this: https://i.stack.imgur.com/ccR6N.png The chart is floating to the left and I would like to have everything centered within ...

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

Replicate and customize identical object for creating instances in JavaScript

I am working with an object that has the following structure: var customObject = function() { this.property = "value"; }; customObject.prototype = new otherObject(); customObject.prototype.property2 = function() {}; This is just a snippet as the ac ...

How to dynamically change the border-top color of an <a> tag in a menu using a jQuery loop

I am interested in adding a colorful border-top to my menu using jQuery. I know this can be achieved with HTML by including style="border-top-color: red;", but I want to explore the jQuery method. Here is what I have attempted so far: var colors = [ ...

What is the best way to send and utilize a variable from app.js in index.ejs?

Why are my attempts to pass variables from app.js to index.ejs not working? I am using Mongoose and EJS, and I want to display database data on my web-page instead of just using console.log(). How can I do this correctly? (app.js snippet followed by inde ...

The issue of video tags not displaying previews on iPhone across all browsers is also accompanied by problems with controls not functioning correctly

As I delve into the world of HTML5 video tags, I encountered an issue where the video wouldn't show a preview frame initially. Instead, only the Resume button would appear. Furthermore, after playing the video with the Resume button, it wouldn't ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

What is the best way to have the slide shift to the left solely after the initial click and prevent it from moving left on subsequent clicks?

Is there a way to prevent the slide area from scrolling left when the left button is clicked before it has been scrolled right first? Additionally, how can we lock the scroll after it reaches the last div? var $slider = $("#recent-container") $("#right ...

Is there a way to send my form via the submission button inside a modal in ASP.NET MVC?

Although it may seem like a simple question to some, I am struggling with understanding how to implement a submit button that opens a modal and displays user input from a text box. The user can then choose to edit their input or proceed with submitting it. ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

The process of implementing image validation in PHP, such as checking for size and weight restrictions,

Can someone assist me with inserting an image in PHP, along with validation for size and weight? If the size or weight is incorrect, I need to display an error message. Please provide guidance... PHP script needed... if (isset($_POST['submit']) ...

Creating custom CSS data-tooltip for image maps without the use of jquery

I stumbled upon the Pure CSS Tooltips (data-tooltip) feature showcased at http://www.frequency-decoder.com/demo/css-tooltips/, and I am eager to implement it on a specific area of an image map in a rectangular shape. However, despite finding a JavaScript c ...

Exploring the Difference Between Index Numbers of Two Arrays in JavaScript

I would like to store the index values of two objects in order to perform a comparison by looping. Currently, I am able to retrieve the index value from the drop-down lists and have a separate script that displays the index number when the dropdown is chan ...

Creating a stunning display of six video textures on a cube through the power of three.js

My current project involves working with a video that has been segmented into six parts. Here is a screenshot of the input video. The goal is to project these 6 videos onto the six faces of a cube using JavaScript: <!DOCTYPE html> <html> &l ...

Unable to hear sound - JavaScript glitch

Spent countless hours trying to figure this out - Can't get the audio file to play when clicking an HTML element. var sound = document.querySelector(".soundfile"); function playAudio() { sound.play(); } document.querySelector(".btn-hold").addE ...

Despite locating the button, Protractor still encounters difficulties when attempting to click on it

I've been having trouble clicking on a button using Protractor. The issue is that even though the driver can locate the element, it still won't click on it. Any assistance would be greatly appreciated. Thank you in advance. Here is the HTML for ...

JavaScript offers a variety of options for creating a link-styled button

Is there a distinction between <a href="javascript:;"></a> and <a href="javascript:void(0);"></a> ? I am looking to create a link-styled button that triggers a JavaScript function when clicked, so I implement the following: ...

Organize an array of objects based on another array in JavaScript

I have been working on sorting an array of objects by comparing it with another object. The goal is to display the selected objects at the top and the rest below them. While I am currently achieving the desired output, I am interested in exploring ways to ...