Utilizing checkboxes to toggle the visibility of a div element with varying headings

By toggling a checkbox, I aim to show or hide the same div with a different heading.

$('#cbxShowHide').click(function() {
  this.checked ? $('#block').show(1000) : $('#block').hide(1000);
});
#block {
  display: none;
  background: #eef;
  padding: 10px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cbxShowHide" />
<label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" id="cbxShowHide1" />
<label for="cbxShowHide1">Show/Hide1</label>
<input type="checkbox" id="cbxShowHide2" />
<label for="cbxShowHide2">Show/Hide2</label>
<div id="block">Some text here</div>

When the "Show/Hide" checkbox is clicked, the text "Some text here" is displayed.

I intend to extend this functionality to multiple checkboxes so that each one can show "some text here" uniquely like "some text here1", "some text here2", and so on.

Answer №1

Check out the jsfiddle link provided for reference. I have restructured the content by moving it from a div into a span.

$('#cbxShowHide1').click(function(){
    $('#block span').text("Your new text for this div")
    this.checked?$('#block').show(1000):$('#block').hide(1000);
});

I hope this explanation is clear and helpful.

Answer №2

Instead of just targeting the click event for a specific ID "cbxShowHide," I updated it to apply to all inputs that are clicked.

$('[type~=checkbox]').click(function(){
    this.checked?$('#block').show(1000):$('#block').hide(1000);
});

$('[type~=checkbox]').click(function(){
    this.checked?$('#block').show(1000):$('#block').hide(1000);
});
#block{display:none;background:#eef;padding:10px;text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" id="cbxShowHide1"/><label for="cbxShowHide">Show/Hide1</label>
<input type="checkbox" id="cbxShowHide2"/><label for="cbxShowHide">Show/Hide2</label>
<div id="block">Some text here</div>

Answer №3

To start, it is important to utilize a class instead of an ID for this functionality to work properly with each individual checkbox.

Additionally, keep in mind that the "for" attribute in a label tag is specific to an ID, so ensure that the label is correctly linked to its corresponding checkbox.

I hope this example serves as a helpful guide:

$('.checkbox').click(function(){
   if($(this).attr('id') == 'cbxShowHide')
   {
        $('#block').text('Some text here')
   }
   if($(this).attr('id') == 'cbxShowHide1')
   {
        $('#block').text('Some text here1')
   }
   if($(this).attr('id') == 'cbxShowHide2')
   {
        $('#block').text('Some text here2')
   }

    this.checked?$('#block').show(1000):$('#block').hide(1000);
});
#block{display:none;background:#eef;padding:10px;text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="checkbox" class='checkbox' id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" class='checkbox' id="cbxShowHide1"/><label for="cbxShowHide1">Show/Hide1</label>
<input type="checkbox" class='checkbox' id="cbxShowHide2"/><label for="cbxShowHide2">Show/Hide2</label>
<div id="block">Some text here</div>

Answer №4

Although not the most stylish, time constraints led me to produce this solution quickly. I hope it fulfills your requirements.

CSS

#sectionA, #sectionB, #sectionC {display:none;background:#eef;padding:10px;text-align:center;}

HTML

<input type="checkbox" id="toggleSectionA"/><label for="toggleSectionA">Toggle Section A</label>
<input type="checkbox" id="toggleSectionB"/><label for="toggleSectionB">Toggle Section B</label>
<input type="checkbox" id="toggleSectionC"/><label for="toggleSectionC">Toggle Section C</label>
<div id="sectionA"><span>Content for Section A</span></div>
<div id="sectionB"><span>Content for Section B</span></div>
<div id="sectionC"><span>Content for Section C</span></div>

JS

$('#toggleSectionA').click(function(){
    this.checked?$('#sectionA').show(1000):$('#sectionA').hide(1000);
});
$('#toggleSectionB').click(function(){
    this.checked?$('#sectionB').show(1000):$('#sectionB').hide(1000);
});
$('#toggleSectionC').click(function(){
    this.checked?$('#sectionC').show(1000):$('#sectionC').hide(1000);
});

Answer №5

Check out this Jsfiddle example:jsfiddle.net/xs523nw8/6/

   $("input[type='checkbox']").click(function(){
       if($(this).is(":checked")){
      $(this).siblings("input[type='checkbox']").removeAttr("checked");
      $("#block").text('Displaying some text here :'+$(this).index());
      $("#block").show(1000)
    }
    else{
      $("#block").hide(1000);
    }
   });

Answer №6

Take a look at this demo https://jsfiddle.net/tz5ror3s/

I've included a new class in the checkboxes and linked a click event to them, displaying the text inside a block span.

$('.cbxShowHide').click(function() {
    $('#block span').text('Here is some additional text ' + $(".cbxShowHide:checked").length );
    $('#block').show();
});

Answer №7

1. Changing text of an element dynamically

View the fiddle

Situation: You only need to toggle the content of the #block element. In this scenario, using type='radio' inputs instead of type='checkbox' is more suitable since you are toggling text in one location and selecting just one option at a time is sufficient.

2. Displaying elements depending on checkbox status

Check out the fiddle

Situation: You want to show or hide multiple boxes based on the checkbox input's state (checked/unchecked).

Upon each change in state, it iterates through the checkboxes and:

  • If a checkbox is checked, the corresponding box with the same number is shown
  • If a checkbox is unchecked, the corresponding box with the same number is hidden

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

Delete the CSS class from a specific HTML element

Having just started learning HTML and CSS, I encountered an issue. I applied a CSS class to a table element. Subsequently, I inserted a child table within the parent table. The problem arose when the CSS class of the parent table also influenced the child ...

The component <FormControl /> does not support the variant prop

It's perplexing to me why <FormControl /> doesn't seem to accept the prop variant. Even though the documentation suggests that this prop is available. import React from "react"; import { render } from "react-dom"; import FormControl from " ...

Using Polymer in Chrome Extension content script

Currently, I am experimenting with incorporating Polymer into a chrome extension. My main objective is to take advantage of styling encapsulation in order for my content scripts to operate independently from the CSS on the visited webpage. To begin, I hav ...

Tips for connecting a suspended div below a Bootstrap 5 fixed navigation bar

I successfully implemented a sticky navigation using Bootstrap 5, and now I want to add a hanging div (.chat-tag) below the sticky nav for a chat feature. This "hanging tag" should stay attached to the sticky nav as the user scrolls down the page. It&apos ...

Stop text from being selected across all browsers in Firefox

My current CSS includes: *{ -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } If you visit http://jsfiddle.net/KyF5x/ and click be ...

Insert an element at the start of a sorted array object

I am currently working on a small application that has the following structure: Posts -> Post -> Comments -> Comment. The Posts component sends a request for an array of posts sorted by date in descending order. Each post also fetches its comment ...

Content in React Router may fail to load when refreshing the page, navigating forward, or manually

I recently started using React and I'm getting familiar with React Router. I divided my application into two main routes because each uses a different style: the Splash path is for when the user first enters, which contains the Splash screen, Login, a ...

Swap out ASP.NET AJAX with jQuery for making ASHX requests

Recently, I have been utilizing the following method to communicate with a Web Proxy for cross domain calls. However, as I am in the process of updating my code and already use jQuery, I am considering dropping ASP AJAX since it is only used for this speci ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

Using JavaScript to transfer the data ID from a button to a form

I am working on a project where I have a button that triggers a modal: <button type="button" class="btn btn-primary add-subscription" data-toggle="modal" data-workspace_id="{{ workspace.id }}" data-target="# ...

Showcasing tooltip when hovering over Font Awesome icon

My datatables grid includes some font awesome icons to represent actions like edit, delete, etc. Here's a visual representation of how they appear: https://i.sstatic.net/W0VQi.png Take a look at the accompanying HTML code: <td> <a a ...

Incorporating jQuery validation rules for dynamically generated elements in ASP.NET

My MVC3 project has dynamically inserted form fields on a page. Due to the complexity of the form, I can't add jQuery validation server-side as usual. The issue arises because multiple fields in the UI contribute to the value of one hidden field, whic ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Is there a way to delete specific information from a JSON response?

Received the service response in the following format: Temp([ { XXX: "2", YYY: "3", ZZZ: "4" }, { XXX: "5", YYY: "6", ZZZ: "7" }, { XXX: "1", YYY: "2", ZZZ: "3" } ]); I need to manipulate this response in J ...

Adjust the alignment of text within the <select> tag to the right in Safari browser

Is there a way to align text right in a select option tag? <select style="direction:rtl;text-align:right"> <option value="" selected="">همه</option> <option value="1">راهبر سيستم</option> <option v ...

Set a variable equal to the output of an external function, but receive an undefined value in

I've been facing an issue where I'm trying to store the value of an external function in a JavaScript variable, but it keeps returning undefined. The external function in question is designed to search for a specific record within a database: f ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

Switch to a different form when clicked using JavaScript

Can you assist me with my code issue? The scenario is as follows: I have two forms - one for registration and one for login. I want to dynamically replace the login form with the register form when the user clicks on the "Sign up" link. Similarly, if the ...