Using JQuery to create a checkbox with dual functionality within a function

I'm struggling to create a versatile checkbox that will toggle the display of a div from none to block when checked, and back to none when unchecked.

I attempted to implement a conditional statement:

$("#customCheck1").on("change", function() {
  if ($(this).is(":checked") || document.getElementById("Reload").style.display = "none") {
    $('#lblauto').text("Auto Reload ON")
    document.getElementById("Reload").style.display = "block";
  } else {
    $('#lblauto').text("Auto Reload OFF")
    document.getElementById("Reload").style.display = "none";
  }
})

However, it seems to not be working as expected.

Below are the necessary codes:

HTML (Checkbox):

<div class="custom-control custom-checkbox" id="checkasd">
  <input type="checkbox" class="custom-control-input" id="customCheck1">
  <label class="custom-control-label" for="customCheck1" id="lblauto"><span>Auto Reload OFF<span></label>
</div>

JQuery:

$("#customCheck1").on("change", function() {
  if ($(this).is(":checked")) {
    $('#lblauto').text("Auto Reload ON")
    document.getElementById("Reload").style.display = "block";
  } else {
    $('#lblauto').text("Auto Reload OFF")
  }
})

I am using Bootstrap v4.3.1

Answer №1

If you're looking to toggle elements using jQuery, you can utilize the toggle function. Start by creating a class to hide the Reload div initially, and then employ toggle to alternate between showing and hiding it.

$("#customCheck1").on("change", function() {
  if ($(this).is(":checked")) {
    $('#lblauto').text("Auto Reload ON")
  } else {
    $('#lblauto').text("Auto Reload OFF")
  }
  $("#Reload").toggle('display')
})
.display {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-control custom-checkbox" id="checkasd">
  <input type="checkbox" class="custom-control-input" id="customCheck1">
  <label class="custom-control-label" for="customCheck1" id="lblauto"><span>Auto Reload OFF</span></label>
</div>

<div id='Reload' class='display'>Reload Div</div>

Answer №2

An issue arises with this particular line of code:

if ($(this).is(":checked") || document.getElementById("Reload").style.display = "none")
. The single = should be replaced with === for clarity and accuracy.

Furthermore, the $().on method allows for the event to be used directly in the callback function, eliminating the need to access the DOM again.

$("#customCheck1").on("change", function(e) {
  var isChecked = e.target.checked;
  if (isChecked) {
    $('#lblauto').text("Auto Reload ON");
    $("#Reload").css('display', 'block');
  } else {
    $('#lblauto').text("Auto Reload OFF");
    $("#Reload").css('display', 'none');
  }
})

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

Issues with displaying iframes on iOS devices, particularly iPhones

There is a strange issue I am encountering with iframes not displaying on certain phones while working perfectly on others. (They show up fine on all android devices) (However, they do not work on iphone 6 and 7 but surprisingly work on 7 plus, 7S, and a ...

Condition has been fulfilled for both ngShow and ngHide

I am attempting to show a loading icon while data is being loaded, and then display the data once it is ready. However, I am encountering a problem where for a brief moment, both the loading icon and the data are visible... https://i.sstatic.net/vDXOG.png ...

Issues rendering ThreeJS geometry data imported from Json file

Having been a dedicated user of this website for some time now, I must admit that this is the first instance where I find myself in need of posting a question. The issue at hand revolves around a Json file from which I extract data and manipulate it with m ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

Display HTML in PHP and set the input value as a PHP variable

I'm struggling with my PHP code and need some assistance. I want to echo an HTML input field with a specific value from a variable, but it's not working as expected. Can anyone provide guidance on what might be going wrong? echo "<input type= ...

When working in Node, leverage the `then()` method to execute functions sequentially

Is there a way to run a loop function synchronously rather than asynchronously without using callbacks or external libraries? File 1 var db = require('./promiseUnderStanding'); var fun = function () { for (var i = 0; i < 10; i++) { ...

Ensuring Unique CSS for Diverse Devices: A User-Agent Driven Approach

I am facing multiple challenges and working towards finding solutions. I have developed a webpage and now I want to redirect the link to the CSS file based on the user agent. `<script type="text/css" src="style.css"> </script>` However, inst ...

Managing the attention on a switch button

I'm struggling to maintain focus on the toggle button after it's been clicked. Currently, when I press the button, the focus jumps to the top of the page. I can't figure out what I'm doing wrong. Below is the code snippet: HTML <b ...

What exactly is a doclet as defined in JSDoc documentation?

//Sample 1 /** * Here we have a simple function that returns a message * @param {String} msg The message to be returned * @returns {String} The message */ function showMessage(msg) { return msg } //Sample 2 /** * This is a function that also retur ...

A guide to designing a responsive flexbox layout with various columns and rows

I need help designing a container that is responsive for both mobile and desktop, resembling the layout shown in this image. The initial HTML structure is as follows, but I can modify it by adding elements or classes if necessary. <div class="conta ...

Accessing multi-dimensional array properties in PHP with JavaScript integration

In my PHP code, I have an array structured like this: <?php $data = array(); $data[0] = array('year' => 2001, 'month' => array( 'January' => array('val1' => 1000, 'v ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

Utilize Moment to round a date either up or down

I am using Moment to compare two datetime values. Specifically, I am utilizing Moment.isSameOrBefore function. However, my two date values are slightly different due to milliseconds. I want these two values to be considered the same: var date1 = ' ...

AngularJS text markers

In order to streamline the process of managing tags with random content, I have devised a 'tag' manipulation system using the angular-ui alert mechanism. The system includes a factory and a directive as follows: Factory: app.factory( &a ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

What steps do I need to take in order to include REMOVE and EDIT buttons in my table?

In the index.html file, there is a teacher table that is only displayed after clicking on the button Teachers: <div class="container"> <table class="teacherTable" border="1" width="100%" cellpadding=&qu ...

What is the best way to set up Flow type checking for functions passed as props in a React and Redux application?

In my app, I've been passing Redux action creators as props and want to improve type checking. Using the generic Function type has limitations, so I tried using the existential operator (*) in my Props type with no success in getting Flow to infer the ...

Clicking on Fixed Positioning triggers a reset

When I activate the sidebar by clicking the menu button, it remains fixed in position until the first scroll. However, if I interact with the sidebar by clicking on it, the button resets and goes back to the top of the page. This issue seems to only occur ...