Selecting the child checkbox within the parent div using ng-click

Is there a way to trigger the click event of a parent div on its child checkbox in AngularJS? The Checkbox will have the attribute hidden, necessitating the parent div to act as the clickable element.

Sample HTML:

  <body ng-app="checkboxApp">
    <div ng-controller="MainController">
      <h1>Hello Plunker!</h1>
      <form name="myForm">
        Value1:<input type="checkbox" ng-model="value1" /><br />
        Value2:<input type="checkbox" value="value-2" ng-model="value2" ng-true-value="YES" ng-false-value="NO" /><br />
        <tt>value1 = {{value1}}</tt><br />
        <tt>value2 = {{value2}}</tt><br />

        <hr />

        <div class="btn btn-primary">
          Value1 (hidden):<input type="checkbox" ng-model="value1" hidden/><br />
        </div>
        <div class="btn btn-primary" >
          Value2:<input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO" /><br />
        </div>
      </form>
    </div>
  </body>

Javascript Code:

angular.module('checkboxApp', []);

angular.module('checkboxApp')
  .controller('MainController', [ '$scope', function MainController($scope){
    $scope.value1 = true;
    $scope.value2 = 'YES'
  }]);

Check out the code on Plnkr: here

I've attempted using a click function() and ng-change, but haven't been successful in getting it to work properly yet.

Answer №1

If you want to add functionality to the parent div, simply include an ng-click attribute like this in your code. This method will work even if you are not using ng-true-value and ng-false-value.

<div class="btn btn-primary" ng-click="value1 = !value1>
  Value1 (hidden):<input type="checkbox" ng-model="value1" hidden/><br />
</div>
<div class="btn btn-primary" ng-click="value2 = !value2>
  Value2:<input type="checkbox" ng-model="value2"/><br />
</div>

Alternatively, you can create a function like this: ng-click="toggle(value2)"

$scope.toggle = function(val) {
    if (val === "YES") {
        val = "NO";
    } else {
        val = "YES";
    }
}

Feel free to check out this Plunker for reference.

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

generate a listing based on an HTTP query

Here is the code snippet from my controller : @RequestMapping("/allU") public List<Utilisateur> AllU() { return UtilisateurRepo.findAll(); } When I try to access this data in my AngularJS code like this : $scope.list=$http.ge ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

Transfer the layout from one HTML file to multiple others without the need to retype the code

I am working on developing an e-commerce website with HTML/CSS. My goal is to have a consistent template for all product pages that are accessed when clicking on a product. However, I do not want to manually code each page using HTML and CSS. Is there a mo ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

Setting default data in a data table that spans multiple pages is a useful feature that can

I am facing an issue with the default settings in the data table where I need the checkbox to be pre-checked on the controller's side. The problem arises when the checkbox is not staying checked after navigating to the second page and beyond. functi ...

Customizing filters to easily decode words

I have been utilizing angular-translate for my project to translate words in views using the following method: However, I am facing difficulties with my filter: angular.module('MyModule') .filter('weekdays', function () { r ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

Creating reactive behavior with a Promise initiated within a constructor - A guide

I am facing an issue with my Thing class. In the constructor, there is an asynchronous operation using fetch. Once the fetch completes, the result is assigned to a field in the Thing object: class Thing { constructor() { this.image = null ...

The installation of the material ui package was unsuccessful

C:\Users\User\Desktop\client4>npm i @material-ui/icons npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] ...

When using Selenium async script in its own thread, it can interrupt the execution of other

Let's consider this situation: Various scripts need to run in the browser. One of them involves sending messages from one browser to another (WebRTC). I am interested in measuring the delay for each operation, especially when it comes to sending mess ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...

Getting started with WebTorrent: A beginner's guide

I have been brainstorming some ideas for using WebTorrent. While I am comfortable with JavaScript and jQuery, I have never ventured into Node.js or Browserify territory. Can someone guide me through how to implement the following straightforward code? var ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

Dealing with promises in React JS JSX: Best practices

Encountering the concept of managing promises within JSX for the first time in my React JS project has been quite interesting. Below is an excerpt from my component's code: import React from 'react'; import Sodexo from './Sodexo' ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

Javascript data table pagination and custom attributes resulting in unexpected truncation of strings

Currently, I have implemented an Ajax functionality in my template to receive a JSON response and dynamically populate a datatable with the elements from that JSON: $('.bicam_tests').click(function(){ $.ajax({ type: 'GET', ...