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

The code is malfunctioning on this site (yet functions perfectly on a different website)

So I have a question that may seem silly, but it's worth asking. I'm attempting to create a sticky div element that stays in place when you scroll past a certain point on the page. This is the script I have: <script type="text/javascript"> ...

Is there a way to change the color of just the most recently clicked anchor element <a>?

I have a sidebar with anchor elements (Link 1,2,3 in my HTML). I want the text color of these anchors to change when clicked. Additionally, I need only one anchor element to be colored at a time, meaning the previous one should return to its normal color. ...

Mobile devices do not support HTML5 Video playback

Here is the HTML5 Video code I am using: <div id="lightBox1" class="lightBox"> <video id="video" controls preload="metadata"> <source width="100%" height="470" src="/ImageworkzAsia/video/iworkzvid.mp4" type="video/mp4"> ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

What are the steps to downloading a server-generated image with user data from the client using Express?

I am facing a challenge with downloading a server-generated image immediately after it is created. My current approach involves using fetch to send user input data (bypassing HTML forms). Although the image is successfully generated on the server, I am str ...

Exploring Azure: Obtain a comprehensive list of application settings from a deployed Node.js web application

After successfully deploying a NodeJs app to a Linux Azure AppService, I am now aiming to retrieve the server settings of this particular app-service. By enabling managed Identity for the AppService under the 'Identity' tab, I attempted to achiev ...

Can the hasClass() function be applied to querySelectorAll() in JavaScript?

As a beginner in javascript and jquery, I recently attempted to manipulate classes using the following code snippet: if ($(".head").hasClass("collapsed")) { $(".fas").addClass("fa-chevron-down"); $(".fas&qu ...

Looking to personalize the MUI - datatable's toolbar and place the pagination at the top?

I successfully managed to hide the toolbar icon, but I am struggling with positioning pagination from bottom to top. Additionally, I am attempting to add two buttons (reset and apply) in the view-Column toolbar without any success in customizing the class. ...

I am struggling to grasp the concept of how the g flag in JavaScript's string.match(regexp) method operates

In the JavaScript book "The Good Parts", there is an explanation of the method string.match(regexp): The match method works by comparing a string with a regular expression. Its behavior varies based on whether or not the g flag is present. Without the g ...

Permitting various valid responses for questions in a multiple-choice test | Utilizing Angular.js and JSON

As a beginner in this realm, I must apologize if my query seems naive. I recently crafted a multiple-choice quiz using HTML, CSS, JavaScript (angular.js), and a JSON data file following a tutorial I stumbled upon. The outcome pleased me, but now I am face ...

Surprise mistake: Jade's error with the length

What can I do to address this problem? The jade file in question is as follows: extends layout block content h1. User List ul each user, i in userlist li a(href="mailto:#{user.email}")= user.username U ...

next-images encountered an error during parsing: Unexpected character ''

Having trouble loading images dynamically with next-images: //Working <Image src={require(`../../images/exampleImage.jpg` )}/> However, I want to use a dynamic URL like this: //Not working <img src={require(`../../images/${image}.jpg` )}/> Th ...

Finding tool for locating object names in JSON

JSON data: [ { "destination": "Hawaii", "Country": "U.S.A", "description": "...and so forth", "images": { "image": [ "hawaii1.jpg", "hawaii2.jpg", ...

Error Loading JQuery: The function $() is not recognized in the Shopify platform

I seem to be overlooking something obvious. I am using Shopify and have included jQuery in the head section of the theme.liquid file: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> This script is placed rig ...

Easy methods to navigate between screens without using React Router libraries

After experimenting with two different methods to switch between screens in a simple application (up to 3 modes/screens), I am still in the learning phase and mainly focusing on practicing with useState and possibly useEffect for certain scenarios. I&apos ...

Developing a custom CSS for React using clamp and focus attributes

I'm currently working on creating an object to be used in inline style, but I'm having trouble figuring out how to correctly write `clamp` and `after`. const PhoneInputStyle = { fontSize: clamp("13px", "1.111vw", "16px"), /*this particular ...

Initiating a click function for hyperlink navigation

Here is the HTML and JavaScript code that I am currently working with: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script> </head> <body> <a href="#f ...

What is preventing jQuery 3 from recognizing the '#' symbol in an attribute selector?

After updating my application to jQuery 3, I encountered an issue during testing. Everything seemed to be working fine until I reached a section of my code that used a '#' symbol in a selector. The jQuery snippet causing the problem looks like th ...

Enhance the user experience with a personalized video player interface

I am facing difficulty in creating a responsive video with custom controls. While I understand that using a <figure></figure> element and setting the width to 100% makes the video responsive, I am struggling with making the progress bar also r ...