Home > OS >  change style through checkbox
change style through checkbox

Time:03-22

I'm working ona fullcalendar project.

I have these 2 checkboxes (Ore Personali e Assenze), when they are checked they should hide the events but at the moment they are not doing it.

This is my input checkbox:

<input type="checkbox" id="OP" name="calendario" value="OP">

And this is the function i've build so far:

$(document).ready(function() {
            $('input[type="checkbox"]').click(function() {
                var checkBox = document.getElementById("OP");
                var x = document.getElementsByClassName("fc-event-container");
                if (checkBox.checked === true){
                    x.style.visibility = "visible !important";
                }else{
                    x.style.visibility = "hidden !important";
                }
            })
        })

I build it by looking on the internet cause i'm new to JS and dont know much, just basic stuff. And it's giving error in the x.style part (telling me is undefined). Can someone explain to me how i should do it, cause on internet i only found this way and some other who's just giving me errors anyway.

thanks in advances whos gonna help me (or at least try)


i did as @Cypherjac suggest and it worked.

But now it just hide the events on the current month, when i change months i have to checked and unchecked to hide. Even if i go back to the month i hid the events they are visible Is there a way to let them stay hide even if i change month?


Before i update the code i will specify that this is not my code, my fullcalendar is from a template i found on internet, i add the function i needed but most of th stuff was already there:

calendar.js code:

key: 'handleFullcalendar',
    value: function handleFullcalendar() {
    
        var myOptions = {
            header: {
                left: 'today',
                center: 'prev,title,next',
                right: 'none',


            },
            
            buttonText:{
                today: 'Oggi',
                month: 'Mese',
                week: 'Settimana',
                day: 'Giorno'
            },
            
            locale:'it',        
            allDaySlot: false,  
            selectable: true,
            selectHelper: true,               
            timeFormat: 'H(:mm)',             
            editable: true,
            eventLimit: true,
            resourceAreaHeaderContent: 'Calendari',
            
            resources: [
                {
                    id: 'a',
                    title: 'Ore Personali'
                },
                {
                    id: 'b',
                    title: 'Assenze'
                }
            ],
            
            windowResize: function windowResize(view) {
                var width = $(window).outerWidth();
                var options = Object.assign({}, myOptions);

                options.events = view.calendar.clientEvents();
                options.aspectRatio = width < 667 ? 0.5 : 1.35;

                $('#calendar').fullCalendar('destroy');
                $('#calendar').fullCalendar(options);
            },
            
    //_______apre modal per aggiungere nuovo evento
        select: function select(event) {                
            $('#addNewEvent').modal('show');
            $('#calendar').fullCalendar('refetchEvents',event._id)
        },
            
    //_______________ELIMINARE EVENTO TRAMITE X
    
         eventRender: function(event, element, view) {
            if (view.name == 'listDay') {
                element.find(".fc-list-item-time").append("<span class='closeon'>X</span>");
            } else {
                element.find(".fc-content").prepend("<span class='closeon'>X</span>");
            }
            element.find(".closeon").on('click', function() {
                var deleteMsg = confirm("Vuoi davvero eliminare "   event.title   "?");
                if (deleteMsg == true) {                        
                    $.ajax({
                        url: 'eventi/deleteEvent.php',
                        type: 'POST',
                        data:  {_id: event.idAssenza, nomeUtente: event.nomeUtente},
                        success: function(html){
                            location.reload();
                        }
                    })
                    $('#calendar').fullCalendar('removeEvents',event._id);
                }else{
                    location.reload();
                }
            })
        }, 
                        
        //triggherà apertura modal di #editEvent
        eventClick: function eventClick(event) {
            var color = event.backgroundColor ? event.backgroundColor : (0, _Config.colors)('blue', 600);
            $('#editEname').val(event.title);
            $('event.id').val(event.idAssenza);
            $('nomeUtente').val(event.nomeUtente);
            $('#editStarts').val(event.start.toISOString());
            $('#editEnds').val(event.end.toISOString());
            $('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
                event.title = $('#editEname').val();
                event.start = $('#editStarts').val();
                event.end = $('#editEnds').val();
                $.ajax({
                    url: 'eventi/updateEvent.php',
                    type: 'POST',
                    data:  {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, },
                    success: function(html){
                        location.reload();
                    }
                });
                $('#calendar').fullCalendar('updateEvent', event._id);
            });
        }, 

            

            events: {                   
                url: 'eventi/load.php', 
                method:'POST'
                //color: <- fare in modo che prenda i colori scelti nel modal
                
            },
            droppable: false
        };
        
{       
    $(function() {
        $('#OP').change(function() {
            var x = $('.fc-event-container');
            // Access the element using jQuery
            if($(this).prop('checked')){
                x.css({
                    'visibility': 'visible'
                })
            }
            else {
                x.css({
                    'visibility': 'hidden'
                })
            }
        })
    });
},

        var _options = void 0;
        var myOptionsMobile = Object.assign({}, myOptions);

        myOptionsMobile.aspectRatio = 0.5;
        _options = $(window).outerWidth() < 667 ? myOptionsMobile : myOptions;

        $('#editNewEvent').modal();
        $('#calendar').fullCalendar(_options);
    }

Calendar.php:

    <?php 
  require_once "config.php";
  session_start(); 
   if(!ISSET($_SESSION['nomeUtente'])){
    header('location:login/login.php');
   }
?>

<!DOCTYPE html>
<html  locale="it">
  <head>

    <!-- Meta Tag -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta name="description" content="bootstrap material admin template">
    <meta name="author" content="">
    
    <title> Calendario | E.D. Elettronica Dedicata </title>
  </head>
  <body>

<div >
      <div >
        <div >
          <i  aria-hidden="true"></i>
          <i  aria-hidden="true"></i>
        </div>
        <div >
          <div data-role="container">
            <div data-role="content">
<!--LISTA CALENDARI-->
              <section >
                <h5 >Lista calendari di <?php echo $_SESSION["nomeUtente"]; ?></h5>
                <div >                  
                  <div  data-plugin="editlist">
                    <div >
                      <input type="checkbox" id="OP" name="calendario" value="OP" checked>
                      <span ><a href="calendarOP.php">Ore Personali</a></span>
                    </div>                    
                  </div>
                  <div  data-plugin="editlist">
                    <div >
                      <input type="checkbox" id="assenze" name="calendario" value="assenze">
                      <span ><a href="calendar.php">Assenze</a></span>                      
                    </div>
                    <div >
                    </div>
                  </div>
                </div>
              </section>

            </div>
          </div>
        </div>
      </div>
      <div >
        <div >
          <div id="calendar"></div>

<!--addEvent Dialog -->
          <div  id="addNewEvent" aria-hidden="true" aria-labelledby="addNewEvent"
            role="dialog" tabindex="-1">
            <div >
              <form  action="eventi/addEvent.php" method="post" role="form">
                <div >
                  <button type="button"  aria-hidden="true" data-dismiss="modal">×</button>
                  <h4 >Aggiungi Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
                </div>
                <div >
                  <div  id=editColor>
                    <label >Tipo:</label>
                    <input list="assenza" name="ename" id="ename" style="margin-left: 15px;" />
                    <datalist id="assenza">
                      <option value="Normali">
                        <option value="Straordinarie">
                      <option value="Ferie">
                      <option value="Malattia">
                      <option value="Permesso">
                        <option value="Smart Working">
                      <option value="Altro">
                    </datalist>
                    <input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">                     
                  </div>
                  <div >
                    <label  for="starts">Inizio:</label>
                    <div >
                      <div >
                        <input type="datetime-local"  id="starts" name="starts" data-container="#addNewEvent">                 
                      </div>
                    </div>
                  </div>
                  <div >
                    <label  for="ends">Fine:</label>
                    <div >
                      <div >
                        <input type="datetime-local"  id="ends" name="ends" data-container="#addNewEvent">
                      </div>
                    </div>
                  </div>                  
                </div>
                <div >
                  <div >
                    <input type="submit"  value="Aggiungi Assenza">
                    <a  data-dismiss="modal" href="javascript:void(0)">Annulla</a>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <!-- End AddEvent Dialog -->

<!-- editEvent Dialog -->
          <div  id="editNewEvent" aria-hidden="true" aria-labelledby="editNewEvent"
            role="dialog" tabindex="-1" data-show="false">
            <div >
              <form  action="eventi/deleteEvent.php" method="POST" role="form">
                <div >
                  <button type="button"  aria-hidden="true" data-dismiss="modal">×</button>
                  <h4 >Modifica Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
                </div>
                <div >
                  <div >
                    <label  for="editEname">Tipo:</label>
                    <input list="assenza" name="editEname" id="editEname" style="margin-left: 15px;" />
                    <datalist id="assenza">
                      <option value="Normali">
                        <option value="Straordinarie">
                      <option value="Ferie">
                      <option value="Malattia">
                      <option value="Permesso">
                        <option value="Smart Working">
                      <option value="Altro">
                    </datalist> 
                    <input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">  
                  </div>                  
                  <div >
                    <label  for="editStarts">Inizio:</label>
                    <div >
                      <div >
                        <input type="datetime-local"  id="editStarts" name="editStarts" data-container="#editNewEvent">
                      </div>
                    </div>
                  </div>
                  <div >
                    <label  for="editEnds">Fine:</label>
                    <div >
                      <div >
                        <input type="datetime-local"  id="editEnds" name="editEnds"data-container="#editNewEvent">
                      </div>
                    </div>
                  </div>
                  
                </div>
                <div >
                  <div >

                    <button  data-dismiss="modal" type="button">Salva modifiche</button>
                    <a  data-dismiss="modal" href="javascript:void(0)">Annulla</a>
                  </div>                  
                </div>
              </form>
            </div>
          </div>
          <!-- End EditEvent Dialog -->

        </div>
      </div>
    </div>
      </body>
</html>

This is the template i'm using it, most of the code it's there, i just update the part i'm using and modifing

CodePudding user response:

Since you're already using jQuery, you can use it to access the elements instead of native js

Here $(this).prop('checked') is being used to check the checked property of the checkbox

Then when it changes, change the visibility of the element based on the current state..

NOTE: The checkbox is checked initially because the element to toggle is visible when the document loads

$(function() {
    $('input[type="checkbox"]').on('change', function() {
        x = $('.fc-event-container')
        // Access the element using jQuery
        if($(this).prop('checked')){
            x.css({
                'visibility': 'visible'
            })
        }
        else {
            x.css({
                'visibility': 'hidden'
            })
        }
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div >
    Toggle the checkbox to toggle me
</div>

<input type="checkbox" id="OP" name="calendario" value="OP" checked>


One thing to note about the calendar is that every time you switch the month, week or day, the events are rendered again.. So that means the events will have their default state which is visible every time you switch through the tabs

So if you want to ensure the element remains hidden you have to access the element only after it has been rendered, because rendering happens sequentially, so you cannot access the element as soon as rendering has started, because by then you can't know when it will render..

So the concept I've introduced is just using the property of the calendar which is dayRender to check when the rendering of the contents is being done, and set a timeout of half a second to return the events back to their initial state..

So that is the concept, you can read through the docs to find an event that will fire after all the rendering of the days is done and then call the function to revert back them to their visible or hidden state

Check the codepen for the working demo

CodePudding user response:

Use onchange event

$(document).ready(function() {
    $('#OP').change(function() {
        var x = document.getElementsByClassName("fc-event-container");
        if (this.checked){
             x.style.visibility = "visible !important";
        }else{
             x.style.visibility = "hidden !important";
        }
    })
});
  • Related