How can JavaScript be used to show a hidden element when a checkbox is selected?

I'm having trouble with a form on my website that has a dropdown box initially hidden using CSS (display: none;). I want to make this dropdown visible (display: inline;) when a checkbox from another element is checked. Can anyone suggest a solution for this?

Specifically, when #Give_to_a_specific_Project is checked, #choose_a_specific_project_from_dropdown should have its display property set to inline in CSS. Here's the HTML code: Codepen: http://codepen.io/mizan/pen/yNbqRa

<form method="POST" action="" class="sc-checkout-form" id="hello_donation_form" data-sc-id="1" data-parsley-validate="" novalidate="">
<div class="sc-form-group">
    <label>
        <input type="checkbox" id="Give_to_a_specific_Project" class="sc-cf-checkbox" name="sc_form_field[Give_to_a_specific_Project]" value="Yes" data-parsley-errors-container="#sc_cf_checkbox_error_1" data-parsley-multiple="sc_form_fieldGive_to_a_specific_Project" data-parsley-id="0210">Give To A Specific Project?</label>
    <input type="hidden" id="Give_to_a_specific_Project_hidden" class="sc-cf-checkbox-hidden" name="sc_form_field[Give_to_a_specific_Project]" value="No">
    <div id="sc_cf_checkbox_error_1">
        <ul class="parsley-errors-list" id="parsley-id-multiple-sc_form_fieldGive_to_a_specific_Project"></ul>
    </div>
</div>
<div class="sc-form-group">
    <select class="sc-form-control sc-cf-dropdown" id="choose_a_specific_project_from_dropdown" name="sc_form_field[choose_a_specific_project_from_dropdown]" data-parsley-id="8242">
        <option value="HeartCrest Educational Center – Tema – Ghana" selected="" data-sc-price="HeartCrest Educational Center – Tema – Ghana">HeartCrest Education</option>
        <option value="Hae Mona Children Home – Sebokeng – South Africa" data-sc-price="Hae Mona Children Home – Sebokeng – South Africa">Hae Mona Children Home</option>
        <option value="Akuafo Farms – Ghana" data-sc-price="Akuafo Farms – Ghana">Akuafo Farms</option>
    </select>
    <ul class="parsley-errors-list" id="parsley-id-8242"></ul>
</div>
<div class="sc-form-group">
    <label>
        <input type="checkbox" id="recurring_monthly_gift" class="sc-cf-checkbox" name="sc_form_field[recurring_monthly_gift]" value="Yes" data-parsley-errors-container="#sc_cf_checkbox_error_2" data-parsley-multiple="sc_form_fieldrecurring_monthly_gift" data-parsley-id="4913">Make this a recurring monthly gift</label>
    <input type="hidden" id="recurring_monthly_gift_hidden" class="sc-cf-checkbox-hidden" name="sc_form_field[recurring_monthly_gift]" value="No">
    <div id="sc_cf_checkbox_error_2">
        <ul class="parsley-errors-list" id="parsley-id-multiple-sc_form_fieldrecurring_monthly_gift"></ul>
    </div>
</div>
<div class="sc-form-group">
    <label>
        <input type="checkbox" id="project_update_by_email" class="sc-cf-checkbox" name="sc_form_field[project_update_by_email]" checked="" value="Yes" data-parsley-errors-container="#sc_cf_checkbox_error_3" data-parsley-multiple="sc_form_fieldproject_update_by_email" data-parsley-id="7080">Receive Project Updates By Email</label>
    <input type="hidden" id="project_update_by_email_hidden" class="sc-cf-checkbox-hidden" name="sc_form_field[project_update_by_email]" value="Yes">
    <div id="sc_cf_checkbox_error_3">
        <ul class="parsley-errors-list" id="parsley-id-multiple-sc_form_fieldproject_update_by_email"></ul>
    </div>
</div>
<button class="sc-payment-btn"><span>Give by Credit Card</span></button>

Answer №1

After reviewing your code, I made several corrections:

  • The jQuery library was not loaded in your CodePen project
  • #specific_project_dropdown was misspelled
  • You were using $(document).ready() incorrectly
  • You tried to use .changed(), which is not a valid event - now we are using .click() instead
  • You were handling the dropdown show/hide functionality incorrectly. Instead of using .next(), you should directly reference it by ID

Here is the updated CodePen project with the corrected code: http://codepen.io/anon/pen/bdWxVE

Updated JavaScript code:

$(document).ready(function() {
    $('#Give_to_a_specific_Project').click(function( event ){
        if ($(this).is(':checked')) {
            $('#choose_a_specific_project_from_dropdown').show();    
        }
        else {
          $('#choose_a_specific_project_from_dropdown').hide();    
        }
    });
});

Answer №2

To trigger the display of the select box, utilize the onchange event of the checkbox. Verify within the onchange function whether the checkbox is checked; if it is, then reveal the select box.

Answer №3

If you have correctly understood the query, accomplishing this task can be done using only CSS, without the need for JavaScript or jQuery. I have created a demonstration for you. Simply click on the [+] symbol to reveal the hidden text.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Toggle Visibility with CSS</title>
  <style>
input[type=checkbox] {
position: absolute;
clip:rect(0 0 0 0)
}
input[type=checkbox]~label span::after{
content: "+";
}
label {
position: absolute;
right: 0;
width: 1em;
height: 1em;
background-color: #fff;
border: 1px solid #000;
color: #000;
text-align: center;
}

/* Default State */
p#show-me {
background: #900;
width: 100%;
text-align: center;
overflow: hidden;
color: #fff;
box-sizing: border-box;
font-size: 1.35em;
margin:0 0 1.5em;
display: none;
}

/* Toggled State */
input[type=checkbox]:checked ~ label span::after{
content: "-";
}
input[type=checkbox]:checked ~ p#show-me{
display: inline;
}
  </style>
</head>

<body>
<input type="checkbox" id="hide">
  <label for="hide" onclick=""><span></span></label>
<p id="show-me">Click on the checkbox to hide this text.</p>
</body>
</html>

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

Looking to Add Dynamic Website Embed Link?

When a user arrives at the website and the Current Top URL is "https://website.com/?code=https://webbbb.com", I need to dynamically set the iframe URL to "https://webbbb.com" for embedding purposes. This way, I can automatically link my complete other web ...

Issues accessing my Facebook account due to domain problems

I have developed an HTML5 game that I am currently running in my web browser. My objective is to integrate Facebook login functionality, so I followed a tutorial and replaced the necessary information with my App ID. However, upon running it, an error mes ...

Implementing a Flexible YouTube Video Display with API Integration

Is there a way to recreate this design? Check out the DEMO HTML <header role="banner"> <div id="wrapper-video"> <video poster="" autoplay loop> <source src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/156843/cut.mp4" ...

Stop users from repeating an action

We are encountering challenges with users repeating a specific action, even though we have measures in place to prevent it. Here is an overview of our current approach: Client side: The button becomes disabled after one click. Server side: We use a key h ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Tips for aligning an icon at the center of a navigation bar using Bootstrap

I'm attempting to design a navigation bar with a hamburger icon on the left and another icon centered. How can I achieve this while maintaining responsiveness? My initial attempt using mx-auto (margin-left margin-right: auto) didn't work as exp ...

Tips for creating a see-through scrollbar in React?

Lately, I've been experimenting with adding overflow-Y: scroll to materialize collections in order to maintain a fixed wrapper height. However, my latest challenge has been figuring out how to make the scrollbars transparent. I've come across sug ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Tips for Successfully Sending Vue Data in Axios POST Call

I'm struggling to pass Vue data to an axios.post request. Using the Vue template doesn't seem to work. How can I successfully pass the Data? Here is my Code: <body> <div id="app" class="container"> <div> ...

Utilize CSS to specifically target the image source within a button and swap it with a different image in the Woocommerce Wishlist Plugin on your Wordpress

I have integrated the Woocommerce Wishlist plugin into my Wordpress website and I am looking to customize the appearance of the 'Add to Wishlist' button. Upon inspecting the source code, I noticed that the button is styled with a GIF image. I wou ...

issues arise with the website background when inserting an SVG image onto the page

I recently created an svg image with a transparent background using Inkscape. I double-checked to ensure its transparency, and I am confident that it is indeed transparent. However, when I uploaded it to my website, it inexplicably added a white backgrou ...

Trouble in Bootstrap design arises when adding extra space causing layout to break

I am trying to add padding or margin between columns. However, whenever I set it in css, the columns end up breaking down. Here is the HTML and CSS code: Currently, without any margin, the 3 columns are displayed correctly but with no space between them ...

How to effectively trigger a function to load images in React

When my react app loads, I want the images to load immediately. This involves calling the function collectionChanged(e.target.value) on application start. Inside a .jsx file, there is a function named getHomePage() which contains 4 functions. Upon calling ...

Personalize the Facebook like button to suit your preferences

I have posted my code on jsfiddle. You can find the link here: http://jsfiddle.net/QWAYE/1/. I have also included another sample code in this link: http://jsfiddle.net/MCb5K/. The first link is functioning correctly for me, but I want to achieve the same a ...

A guide to extracting iFrame information (specifically the referring URL) using JavaScript

Is there a way to retrieve the information from an iFrame (right-click on an iFrame in the browser -> This Frame -> View frame info)? I'm particularly interested in obtaining the referring URL. So far, I managed to retrieve the address using co ...

Closure-compiler and its peculiar pre-codeyntax

When it comes to minimizing my JS code, I typically rely on the online closure compiler available at . Recently, I've been attempting to incorporate this process into PhpStorm using "External tools," but I seem to be encountering a strange issue. Ever ...

Displaying BlockUI Growl notifications at the bottom right using Jquery

I have successfully implemented a growl notification using BlockUI for jquery. However, I am facing an issue where the notification is appearing at the top right and I want it to be at the bottom right instead. After modifying the CSS property to bottom:1 ...

Function that transposes two strings from top to bottom instead of left to right within an array

My current challenge involves transposing two strings vertically instead of horizontally using javascript. I'm contemplating whether to employ the map() and slice() methods for this task. The input will be an array containing two strings, and my goal ...

Can a single character within a span be located and customized using only CSS techniques?

My inquisitive mind believes that the answer lies in the negative, however, CSS3 pseudo-selectors have the ability to work their magic almost like performing illusions on a stage. In an absurd context, I am determined to locate and style the period charac ...

Setting up Raycasting in React-three-fiber: A Guide

I have been experimenting with setting up a scene in react-three-fiber that involves using a raycaster to detect object intersections. You can check out my Scene here. While researching, I came across examples like this one and this other example, but th ...