Display or conceal a div based on checkbox selection

I am trying to implement functionality to show/hide a div when a single checkbox is selected. Currently, it works with "Select all" but I am struggling to make it work with a single checkbox. Below is the code for "Select All":

JS:

<script language='JavaScript'> 
var checkboxcount = 1;

function doCheckOne() {
    if(checkboxcount == 0) {
        with (document.messageform) {
            for (var i=0; i < elements.length; i++) {
                if (elements[i].type == 'checkbox') {
                    elements[i].checked = false;
                document.getElementById('mail_delete_button').style.display = "none";
                }
            }
            checkboxcount = checkboxcount + 1;
        }
    } else
    with (document.messageform) {
        for (var i=0; i < elements.length; i++) {
            if (elements[i].type == 'checkbox') {
                elements[i].checked = true;
            document.getElementById('mail_delete_button').style.display = "block";
            }
        }
    checkboxcount = checkboxcount - 1;
    }
}
</script>

HTML:

<a href="javascript:void(0);" onclick="doCheckAll();this.blur();">Select all</a>
<div id="mail_delete_button" style="display: none;"></div>

I want to display the div "mail_delete_button" when a single checkbox is selected and hide it when no checkboxes are checked. Please note that my input field is in the form "messageform." Here is my input code:

<input type='checkbox' name='delete_convos[]' value='{$pms[pm_loop].pmconvo_id}'>

Your assistance on this issue would be highly appreciated! Thank you! :)

Answer №1

Does something like this work? I added an id="chk" to the checkbox.

<input type='checkbox' name='delete_items[]' value='{$items[item_loop].item_id}' id="chk">

document.getElementById("chk").onclick = function() {
    document.getElementById('delete_button').style.display = this.checked ? "block" : "none";
}​

Check out the DEMO here!

Answer №2

If you're working with jQuery, you might find this tip useful. By utilizing jQuery's toggle() function, you can easily display or conceal div elements based on the checkboxes that are checked. In the code snippet below, the div blocks are initially hidden using the CSS display property set to none.

$(document).ready(function(){
  $('input[type="checkbox"]').click(function(){
    var value = $(this).attr("value");
    $("." + value).toggle();
  });
});

For a practical demonstration, check out: How to Toggle Div on Checkbox 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

Module specifier "vue" could not be resolved due to an uncaught TypeError. Remember that relative module specifiers must always begin with "./", "../" or "/"

Looking to create the most basic vuejs Hello World application using separate files. Here is the project setup: start by creating index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Error: It seems that the window object is not defined when trying to run Firebase analytics

Encountering the error ReferenceError: window is not defined when attempting to set up Firebase analytics in my Next.js project. Below is the code snippet causing the issue: const app = initializeApp(firebaseConfig); const auth = getAuth(app); let analyti ...

Having trouble making "jQuery.inArray" function properly in my code

Recently, I made a small interaction where list items are displayed and rotated when clicked - check it out here: http://jsfiddle.net/S79qp/430/ Lately, due to compatibility issues with IE8, I had to switch from using .indexOf() to jQuery.inArray. However ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...

Guide to efficiently utilizing flex to horizontally position two elements next to each other in a Material UI and ReactJS environment

I have successfully achieved side-by-side components of two cards from Material-UI. However, I am facing an issue when expanding one of the cards. The problem is that Card 1 automatically expands to match the size of Card 2 when Card 2 is expanded, even th ...

I am facing difficulty in loading another page due to AngularJS restrictions

How can I create a link that redirects to another page without any visible effect on the current page? I have tried various methods: <a href="url"> <a href="url" target="_self"> <a ng-click="register()"> The "register" function i ...

Searching Text Boxes with Javascript: A Better Way to Handle Arrays

I'm struggling to implement a feature where users can search for authors in a database and be redirected to the corresponding HTML if found. Otherwise, it should display a message saying "No Author Found"... I need some assistance in getting this fun ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

Having trouble accessing the property of undefined in material ui cards

Currently, I am incorporating Material UI cards into my React project. One issue I encountered is trying to implement two functions, onMouseOver and onMouseOut, in my cards. However, when I run the code, I receive an error message stating "Uncaught TypeE ...

Transferring information from JavaScript to PHP

I am trying to send both the data and text that are within a single DIV tag using JavaScript into PHP values. However, I am encountering an issue with the following code: <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq ...

React app experiencing inconsistent loading of Google Translate script

In my React application, I have integrated the Google Translate script to enable translation functionality. However, I am facing an issue where the translator dropdown does not consistently appear on every page visit. While it sometimes loads properly, oth ...

You have encountered an error: Uncaught TypeError - the function (intermediate value).findOne is not defined

Encountering an error when attempting to call the getStocks function from a Vue component. smileCalc: import User from "../models/user.js"; let userID = "62e6d96a51186be0ad2864f9"; let userStocks; async function getUserStocks() { ...

Auto play feature malfunctioning in Onsen-UI Carousel attribute settings

When utilizing onsen UI in my mobile web application, I encountered an issue with the autoplay property not functioning properly within the carousel. <ons-page> <ons-toolbar> <div class="left"> <ons-toolbar-button on ...

Steps for setting an array of ObjectIds in Mongoose

Running tests on the fixture population in mongoose. const mongoose = require('mongoose') const { ObjectId } = require('mongodb'); const app = require('express')() mongoose.connect('<connection fine>', { useN ...

I am looking to create an extension that can automatically paste text from a variety of lists, but unfortunately, I am struggling to get it up and running correctly

I'm having trouble pasting text into text boxes or documents. I've tried various methods, but nothing seems to work. Am I missing something? Is there a solution or could I get some assistance? manifest.json { "manifest_version": 3, ...

Using Selenium webdriver to assign a JSON object to a paragraph element

What is the correct way to insert a JSON object into a p tag inside an iframe? I attempted the following approach but it displayed the text "[object Object]" rather than the actual content of the object... This is my implemented code: var arrJSON = [ ...

AJAX request made to a specific local directory, instead of the usual localhost

Currently, I am working on a project to create a database that can be filtered using various options. My approach was to keep it simple by using HTML for sliders and checkboxes, along with JavaScript/jQuery for filtering the results. This setup allows me t ...

The initial row's Id will be used as the Id for all subsequent rows within a JSON object

After dragging a tr in a table and confirming by clicking a button, I need the order list to be updated in the database. To achieve this, I created a JSON object where I intend to save the ids and their corresponding new orders. The issue I am facing is t ...

Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there. I am curious to know how I can transform the code below from an OnClick event to a timed event. For instance, I would like to refres ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...