The checkbox remained unchanged when I first tried to toggle it using ng-change

When I click on the checkbox input, nothing happens the first time. But when I click it again the function in ng-change() works as expected.

I am confused. Am I missing something?

<tr dir-paginate="product in kitchenProducts | itemsPerPage: 10">
  <td>
    <img ng-src="{{ product.images.full_size }}" class="table-thumbnail-product" alt="">
  </td>
  <td>{{ product.name }}</td>
  <td>Sandwich</td>
  <td>{{ product.price }}</td>
  <td>
    <label class="toggle toggle-balanced">
      <input type="checkbox" 
             ng-model="productToggleButton" 
             ng-checked="product.is_enabled" 
             ng-change="toggleProductEnable(product.is_enabled,product.id)" value="{{ product.id }}" 
             class="">
      <div class="track">
        <div class="handle"></div>
      </div>
    </label>
  </td>
</tr>

JavaScript Code:

$scope.toggleProductEnable = function(productSelected, productId) {
  console.log(productId);
  if (productSelected) { //If it is checked
    alert('checked');
  } else {
    alert('unchecked');
  }
}

Can someone help me figure out why this is happening?

Thank you!

Answer №1

Your task is quite straightforward, as demonstrated below:

<input type="checkbox" ng-model="mymodel" ng-change="callmyfunction(item.myID)" /> 


$scope.callmyfunction= function (myID) {
   if($scope.mymodel){ //If it is checked
       alert('checked');
   }else{
      alert('not checked test');    
}
}

For your scenario, make sure to remove ng-checked="product.is_enabled"

$scope.toggleProductEnable = function(productSelected, productId) { console.log(productId); if ($scope.productToggleButton) { //If it is checked alert('check'); } else { alert('uncheck'); } }

Answer №2

When using the check input type, we can utilize the checked attribute to determine if the input field is selected or not.

<input type="checkbox" ng-model="mymodel" ng-change="callmyfunction(item.myID)" class="checkbox"/>

let checkboxElement = document.querySelector('.checkbox')
if (checkboxElement.checked == true) { alert('The checkbox is checked')}
else {alert('The checkbox is not checked')}

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

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

Navigating through various Headers in ReactjsHandling different Headers in Reactjs

I am currently working on a project using Reactjs (Nextjs) and I need to have different headers for the home page compared to the rest of the pages. I have created a "Layout.js" file where I have placed the header and footer components, and then imported ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

Activate the function within the same class only for the selected item

Hello there, I'm struggling to grasp how to make this particular functionality work. Basically, I have 8 divs, each containing an image used as a button with the same class (tm-img), and hidden divs with additional information. My goal is to initiall ...

actions with frontend routing for CRUD operations

Imagine you are creating a simple CRUD todo application. Whether you choose to use Angular, React, or Vue for routing, the setup will be similar: /todos => see all todos /todos/:id => view one todo by id /todos/:id/edit => edit one todo by id /t ...

Simplest method for storing small amounts of data

As a beginner in coding, I may be asking a question that seems obvious to some. I successfully created a web app using html/JavaScript that collects user input and transforms it into a variable of my interest. The data I want to extract is stored in an arr ...

What causes Three.js OBJ conversion to render as mesh successfully but log as undefined?

I'm just getting started with Three.js and I'm experimenting a lot. Although I'm new to Javascript as well, the issue I'm facing seems to be more about variable scoping and callback function protocols than it is about Three.js itself... ...

Struggling to align images side by side using HTML and CSS along with figcaption and buttons

Adding buttons below images on my webpage is proving to be a bit challenging. I tried using the figcaption tag, but it resulted in the images stacking on top of each other instead of side by side. **My HTML:** <section class="mostpurch"> ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

Scanning a barcode on the Google search page activates a specific event

I am looking to replicate the functionality seen on Google's search page where any user input, whether through keyboard or barcode scanner, automatically populates the search box. The input should be captured no matter where on the page it happens, wi ...

Accessing personalized services within an AngularJS directive

angular.module("quickquiz-builder").service("SettingsService", function ($http, $q) { var self = { 'generalSettings': [], 'fetchGeneralSettings' : function(){ var d = $q.defer(); $http({ ...

Sending HTML input data to jQuery form field

Is there a way to pass HTML text input values into a Stripe form? Here is an example of what I currently have: <input type="text" name="trip" id="trip" value=""> JS: (part of the form) .append(jQuery('<input>', { 'nam ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Displaying Live Data to Users on Rails 3 using Node.js and MongoDB

I am experiencing an issue with my Rails web application where the data is not being displayed in real-time to users. Despite having a node.js server that is continuously updating a cloud database accessible by the Rails app, the data does not appear insta ...

Creating a predictive text feature using AngularJS and jQuery

Currently, I'm developing a web application that utilizes: JQuery AngularJS Kendo framework Specifically, I am tasked with implementing an auto-complete feature using Kendo on an input text field. Initially, my approach was to target the inp ...

Creating a Python server for an Angularjs application and capturing user input

Can you offer me some assistance, whether it's just a hint or a useful tip that could improve my current approach? I have created a series of forms using HTML and AngularJS. Each form collects input data from users, which is then stored in a JSON str ...

What characteristics do you use to distinguish a non-compiled language?

Curiosity strikes me as I notice a common theme of "personal preference" regarding the distinctions between "Scripting Language" and "Programming Language". Here is my query: Is there a specific technical term for a language that operates without the nee ...

What is the most efficient way to transfer a large volume of documents from mongoDB using http?

I'm dealing with a large mongoDB database that contains millions of documents and I need to fetch them all at once without crashing or encountering cursor errors. My goal is to send this data over http using express in nodeJS. The collection contains ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...