Efficient Checkbox Implementation in ActiveAdmin for Rails 3.1

This query actually encompasses two related inquiries.

  1. Enabling "Select all" functionality - In the realm of formtastic, which is used by Active_admin to render forms, how can I implement a button that selects all checkboxes present on the page? While achieving this using JavaScript is plausible, I am uncertain about the process within formtastic.
  2. Adjusting collection based on selection: Within a dropdown menu offering a list of courses for selection, I aim to dynamically display a checkbox list containing students enrolled in the chosen course. Essentially, the list of students ought to update based on the course selected by the user.

    course.rb

    has_and_belongs_to_many :students

    student.rb

    has_and_belongs_to_many :courses

Answer №1

If you're looking to implement a "select all" checkbox with Formtastic and JQUERY, here's how you can do it:

First, in your student.rb model, add the following code:

attr_accessor :select_all_courses

f.inputs "Courses" do
  f.input :select_all_courses, :as => :boolean, :label => 'SELECT ALL', :input_html => {:onclick => "jQuery.each( $('.student_courses_checkboxes'), function() { this.checked = $('.all_selector')[0].checked });", :class => "all_selector"}  
  f.input :courses, :as => :check_boxes, :collection => @courses, :input_html => {:class => 'student_courses_checkboxes'}      

However, please note that the only option in active admin with formtastic is:

In your course form

f.input :students, :as => :check_boxes, :collection => @students   

Answer №2

To streamline the process of adding Select All/Select None buttons to checkbox group inputs, I incorporated a snippet of javascript into active_admin.js (which I renamed from active_admin.js.coffee as CoffeeScript wasn't being utilized).

//= require active_admin/base

$( document ).ready(function() {
    var $select_btns = $('<li class="choice"><div class="select-btn-container"><button class="select_all">Select all</button><button class="select_none">Deselect all</button></div></li>');
    $('.inputs .check_boxes').each(function (i, el) {
        $(el).find('.choices-group').prepend($select_btns.clone());
    });

    $('.inputs')
        .on('click', '.select_all', function () {
            var $check_boxes = $(this).parents('.choices-group').find('input');
            $check_boxes.each(function () {
                this.checked = true;
            });
            return false;
        })
        .on('click', '.select_none', function () {
            var $check_boxes = $(this).parents('.choices-group').find('input');
            $check_boxes.each(function () {
                this.checked = false;
            });
            return false;
        });
});

This implementation has been tested on ActiveAdmin 1.0.0 with Rails 4.0.4. Hopefully, this solution proves beneficial.

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

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

Vue plugins that emit events

In the scenario where I have a basic Vue plugin that does not contain any components, but simply provides some methods to the user: export default { install(Vue, options) { // Unrelated tasks go here. } Vue.prototype.$foo = () => { ...

Is there a way to successfully include an apostrophe in a URL?

I am currently utilizing Node.js: var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request(url, POST, ...) This method is not functioning as expected! Facebook seems to be c ...

Troubleshooting issue with displaying favicons in express.js

Currently, I am working on a simple express.js example and trying to get favicons to display properly. Everything functions correctly when testing locally, but once uploaded to my production server, only the default favicon appears. I have attempted cleari ...

Unable to locate web element using Selenium in C#

Here is the HTML code I am currently using: <div class="modal-footer"> <button class="btn btn-primary" type="button" value="Show Alert" ng-click="questions.getIrMessage()" data-dismiss="modal">Confirm</button> <button class ...

What is the best way to create a JavaScript button that can be clicked to increase a variable by 1?

I am curious to know how you can create a button that appears on an empty HTML canvas and, when clicked, adds +1 to a variable. I am working on this JavaScript code within an HTML text file which will later be saved as an HTML file. Please ensure that th ...

Steps for assigning distinct identifiers to information entered through an input form

I have a question that I just can't seem to figure out: So, I have this input form: <form @submit.prevent="customSubmit"> <label>Name</label> <input type="text" v-model="newUser.name" id=&quo ...

Switching the vertical alignment of grid items in Material UI when the page is collapsed

When the page is collapsed, the Left grid item element moves to the top of the page and the Right grid element is positioned below it. I would like to reverse this behavior so that the Right element appears on top and the Left element below when the page ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...

Arranging elements on a webpage using Javascript

Creating a Dynamic Div Layout with JavaScript I have successfully implemented functionality wherein clicking on + opens a div and clicking on - closes it. However, I am now faced with the challenge of handling multiple divs at runtime. How can this be ach ...

Using the goBack function in React Router does not add the previous location to the stack

In React Router v4, I have a list page and a details page in my web application. I want to implement a 'Save and close' button on the details page that redirects the user back to the list page when clicked. However, I noticed that after the user ...

The function 'myfunc' was called within a render, however, it is not defined in the instance

I keep seeing this error message Property 'myfunc' was accessed during render but is not defined on instance, and I'm not sure why. Below are my HTML and JavaScript code snippets. const ListRenderingApp = { data() { return { todo ...

Retrieving data from a collection with the find() method in a custom date format

Schema for Customer Data Customers.js import mongoose from 'mongoose'; const Customers = mongoose.Schema({ CustomerID: { type: String, default: "" }, Name: { type: String, default: "" }, Email: { type: String, default: "" }, Pho ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

Tips for transitioning frontend JS to Angular 2 for seamless integration with a PHP MVC backend system

I currently have a robust PHP MVC web application that utilizes jQuery for click events and modal dialog rendering. To align with up-to-date frontend technologies, I am looking to revamp the JavaScript code to function within Angular 2. However, I am faced ...

Show a string on different lines

I'm looking to format my string so that it displays on multiple lines. I attempted to use replaceAll(",", "\n"), but it didn't work as expected. Here's the code snippet: <template> <v-form> <v-container> ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

Adding Tooltips to Your Bootstrap 5 Floating Labels Form: A Step-by-Step Guide

Can you include tooltips or popovers in Bootstrap 5 floating labels text? I've set up a form with floating form fields and I'd like to provide instructions for certain fields using tooltips or popovers. I can make it work with the standard form ...