Using JavaScript to ensure that a div is not hidden on page load if a checkbox is unchecked

Upon inspecting a page, I am implementing a script to check if a checkbox is selected. If not selected, the goal is to hide a specific div element. While troubleshooting this issue, I suspect the problem may be due to the lack of an inline element within the div; however, that approach is not viable in this scenario. Additionally, I have integrated cookies to remember user selections. The cookie function operates correctly, but the functionality to hide the div remains ineffective. Below is the relevant code snippet:

  function setCookie(c_name,value,expiredays) {
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate)
}

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1 
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end))
        } 
    }
    return null
}

function checkCookie(){
document.getElementById('john').checked = getCookie('calOption1')==1? true : false;
document.getElementById('steve').checked = getCookie('calOption2')==1? true : false;
$(document).ready(function() {
    if ($('#john').is(':checked')) {
       $('.ms-acal-color2').css('display', 'block');
    }else{
    $('.ms-acal-color2').css('display', 'none');
    }
});

$('#john').change(function() {
if (this.checked) { //if ($(this).is(':checked')) {
      $('.ms-acal-color2').css('display', 'block');
} else {
      $('.ms-acal-color2').css('display', 'none');
};
}); 

}

function set_check(){
setCookie('calOption1', document.getElementById('john').checked? 1 : 0, 100);
setCookie('calOption2', document.getElementById('steve').checked? 1 : 0, 100);
}

Additionally, refer to the provided HTML code:

<div style="float: left;">
  <div id="myForm">
    <input type="checkbox" onchange="set_check();" id="john"/>
    <label>Show John</label>
      <input type="checkbox" onchange="set_check();" id="steve"/>
      <label>Show Steve</label>
  </div>
</div>

Answer №1

Your coding style needs some improvement as you are mixing JavaScript syntax with jQuery which isn't recommended. It's best to stick to one language for consistency.

You're also making the mistake of adding a document ready listener inside a function and other event listeners, causing confusion in your code.

I have tidied up your code and you can view the improved version here: http://jsfiddle.net/Hezrm/
To see how it works with cookies enabled, check out this link: http://jsfiddle.net/promatik/Hezrm/show

Here are the modifications made in JavaScript:

// When Document Ready, check for cookies and hide unchecked checkboxes
$(document).ready(function() {
    checkCookie();
    $(".person:not(:checked)").next().hide();
});

// This change eventlistener will dynamically show/hide people based on checkbox state
$('#john, #steve').change(function() {
    if( $(this).is(':checked') ) $(this).next().show();
    else $(this).next().hide();
    set_check(); // Save changes to cookies
}); 

function checkCookie(){
    $('#john').attr("checked", getCookie('calOption1') == 1 ? true : false);
    $('#steve').attr("checked", getCookie('calOption2') == 1 ? true : false);
}

function set_check(){
    setCookie('calOption1', $('#john').is(':checked')? 1 : 0, 100);
    setCookie('calOption2', $('#steve').is(':checked')? 1 : 0, 100);
}

A new class .person has been added to facilitate hiding or showing the checkboxes more efficiently:

<input type="checkbox" id="john" class="person"/>

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

PhpStorm IDE does not recognize Cypress custom commands, although they function properly in the test runner

Utilizing JavaScript files within our Cypress testing is a common practice. Within the commands.js file, I have developed a custom command: Cypress.Commands.add('selectDropdown', (dropdown) => { cy.get('#' + dropdown).click(); } ...

What is the best way to create inline-block elements that stretch the entire width of their container?

How can the input field and button behavior be optimized for this specific display: ...

Employing various Class Methods based on the chosen target compiler option

Is there a way to instruct TypeScript to utilize different implementations of methods within the same class, based on the specified target option in the tsconfig.json file? I am currently transitioning one of my scripts to TypeScript to streamline managem ...

Tips for including event information in a form submission using Ajax and jQuery

I have successfully implemented the code below to send a request to the backend using ajax/jquery. My goal: Now, I am looking to dynamically capture form input data when the user interacts with the input fields and include this data in the ajax request. ...

"Troubleshooting the issue of null values in ASP.NET Core Razor Pages when using Ajax POST

I'm currently working on an ASP.NET (6.0) Razor Pages project where I am facing an issue with posting data using AJAX. Despite my efforts, the posted data always ends up being null. Even after going through similar questions on Stack Overflow, I have ...

Move the divs within the overflow container by sliding them, then take out the initial element and append it to the end

Currently, when I utilize .appendTo(".wrapper") as shown in the code below, it eliminates the animation effect. My goal is to have the div on the far left slide out of view, triggering an overflow hidden effect, and then be placed at the end of the slide c ...

The argument 'TabsCtrl1' is throwing an error as it is not recognized as a valid function and is showing as

I have encountered a problem with my controller, and I am seeing the following error message: Error: [ng:areq] Argument 'TabsCtrl1' is not a function, got undefined http://errors.angularjs.org/1.3.0-beta.11/ng/areq?p0=TabsCtrl1&p1=not%20a%20 ...

What is the best way to display two tables together using inline styling?

I attempted to display 2 tables inline by setting their display property to inline, but unfortunately, it did not work as expected. Is there a more straightforward way to achieve the desired inline display for these tables? table { display: inline; } ...

Tips for gathering an array of checkboxes within a dynamic array of items using Vue.js and Vuetify

I am currently working on a role permission system where I have defined a resource array containing items that users can access, as well as checks representing the permissions for each resource. My goal is to dynamically assign a role with these resources ...

Allow only specific classes to be accepted for drops in jQuery UI Droppable

I am facing an issue with my draggable and droppable div elements. I have three divs, all with the class abs, but only one of them also has the additional class outside. My goal is to drag and drop the divs, but I do not want the div with the class outside ...

Managing the React Router component as a variable

I'm currently working on integrating React-Router into an existing React app. Is there a way to use react-router to dynamically display components based on certain conditions? var displayComponent; if(this.state.displayEventComponent){ {/* ...

Choosing Between Methods and Computed Properties in Vue.js

Can you explain the primary distinction between a method and a computed property in Vue.js? I'm finding it tricky to differentiate between the two as they appear quite similar. ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

Encountering insurmountable obstacles in accessing AliExpress

I'm looking to extract specific information from aliexpress using scrapy and selenium. However, I've encountered an issue where the HTML code appears differently when inspecting with Chrome compared to viewing the source. It seems that the conte ...

Is there a way to store cookies in my Firefox Profile using Selenium in Python and retrieve them for the next session?

Lately, I've been using Selenium with Firefox to automate logging into various websites, searching for specific keywords, watching YouTube videos, and then closing the browser after a short period. My goal was to track how the recommended videos chang ...

What is the best way to retrieve and display data from a JSON object that has been encoded using json_encode on one page.php, in another page.php?

I have a specific requirement that involves calling JSON data from one PHP page and displaying it on another PHP page. Can someone guide me on how to achieve this? Below is the JSON code that I need to retrieve: <?php include("Connect.php"); $Db = m ...

The virtual method 'android.location.Location' was called in error

I'm using WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, options) from MobileFirst to retrieve a device's location. Initially, everything works smoothly as I successfully obtain the location. However, after clearing t ...

Acquiring JSON data through the use of jquery and php

Below is the HTML code I am working with: <div id="myDiv"> <p class="readMore"></p> <p class="readMore"></p> <p class="readMore"></p> </div> This is the jQuery function I am using: UPDATE <script> ...

Every key must be a string or number; received a function instead

I encountered a peculiar situation while working with Cucumber: Scenario Outline: Protractor and Cucumber Test InValid Given I have already...... When I fill the <number> .... Examples: | number|... | 3 |... |4 |... Moreover, I ...

Efficiently utilizing CSS classes

My dilemma involves styling a textfield in two different locations on my website, each with its own parent element. The second location requires an additional margin-top that the first does not. What is a clever way to adjust the original margin-top withou ...