Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically.

<!DOCTYPE html>
<html >

  <head>
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
  </head>

  <body ng-app="ngToggle">
    <div ng-controller="AppCtrl">
        <input type="checkbox" ng-model="dean" ng-click="btnChange($event, values, 1)" id="one" name="one" class="here" >
        <input type="checkbox"  ng-model="armada" ng-click="btnChange($event, values, 2)" id="two" name="one" class="here" >
        <!--<p ng-repeat="btn in btns">-->
        <!--  <input type="checkbox" ng-model="btn.bool" class="here" > {{ btn.value }}-->
        <!--</p>-->
        {{btn  }}
        {{values  }}
    </div>
    <script type="text/javascript">
        angular.module('ngToggle', [])
            .controller('AppCtrl',['$scope', function($scope){
            $scope.btns = [{}, {}, {}];
            $scope.values = [];
            $scope.btnChange = function(event, model, val){
              _this = angular.element(event.target);
              x = _this.prop("checked");
              if(x){
                model.push(val);
              }else{
                index = model.indexOf(val);
                model.splice(index, 1);
              }
            };
            angular.element("#one").triggerHandler("click");
        }]);
    </script>
  </body>
</html>

Check out the plunker here: http://plnkr.co/edit/7DpCvkKLlKhRc3YwFTq0?p=preview

Answer №1

If you have incorporated jQuery into your page, you can easily achieve this:

 $(function(){
     angular.element("#one").trigger("click"); 
 });

A straightforward jQuery approach would be:

 $(function(){
    $("#one").click(); 
 });

If you prefer an angular solution (as mentioned by others), you can use the following code:

angular.element(document).ready(function() {
    angular.element("#one").trigger("click"); 
}); 

http://plnkr.co/edit/0OHDIVB2JGqDZnF56E6M?p=preview

It is important to wait for the entire document (or in this case, the checkbox) to be fully loaded before triggering the click event on it.

Answer №2

Placing it on the controller can be done like this:

 angular.element(document).ready(function() {
          angular.element("#one").trigger("click"); 

        }); 

Check out the demo on Plunker

Answer №3

If you want to trigger a click event, consider adding a small timeout before doing so.

$timeout(function() {
          angular.element('#one').click();
        }, 100);

I have made changes to your Plunker link, feel free to check it out Plunker

Alternatively, you can also use the following code snippet:

angular.element(document).ready(function() {
          angular.element("#one").trigger("click"); 
        }); 

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

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

Unit testing in AngularJS: Initializing the controller scope of a directive

Here is the code for a directive with a separate controller using the "controller as" syntax: 'use strict'; angular.module('directives.featuredTable', []) .controller('FeaturedTableCtrl', ['$scope', function ($sco ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

Is there a way to configure MaterialUI XGrid filters to target and filter by the renderCell parameters instead of the backend data source?

While utilizing MaterialUI XGrid to showcase rows of information, I am facing an issue with filtering. Currently, filtering can only be done based on the backend row values rather than what is displayed in the cell. For instance, consider a column named U ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

Tips for closing process.stdin.on and then reopening it later

I've been facing a challenge with an exercise. In this exercise, the client will input a specific integer x, followed by x other y values separated by spaces. The output should be the sum of each y value, also separated by spaces. For example: Input: ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

JavaScript does not allow executing methods on imported arrays and maps

In my coding project, I created a map named queue in FILE 1. This map was fully built up with values and keys within FILE 1, and then exported to FILE 2 using module.exports.queue = (queue). Here is the code from FILE 1: let queue = new.Map() let key = &q ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...

HTML5 - Ajax - puzzling behavior that I am unable to comprehend

Need Help Clarifying My Issue: I currently have a Div with Page 1 content. Page 1 contains a button that transitions the div content to Page 2. Page 2 has a button that switches the div content back to Page 1. The Problem: If Page 1 is loaded first, t ...

What is the best way to create a floating navigation bar that appears when I tap on an icon?

As a beginner in the realm of React, I recently explored a tutorial on creating a navigation bar. Following the guidance, I successfully implemented a sidebar-style navbar that appears when the menu icon is clicked for smaller screen sizes. To hide it, I u ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

Should the button be eliminated in favor of simply requesting input from the user?

Looking for help with my code. How can I set it up so that when the HTML file is clicked on, it prompts for input instead of displaying a button? I'm new to coding and could use some guidance. <!doctype html> <html> <head> <meta ...

Is there a way to detect when the mobile keyboard is open in a React application?

I am currently working with a Textfield that includes the Autofocus attribute. I am wondering if there is a method to detect when the keyboard opens in mobile view and then store this information in a boolean variable. https://i.stack.imgur.com/z0EtB.png ...