jQuery UI Datepicker antes de la opción ShowDay

La interfaz de usuario jQuery beforeShowDay es una opción en Datepicker . Usando esta opción podemos llamar a cualquier función usando cada día. Esto se ejecuta antes de mostrar el calendario.

No queremos que los usuarios seleccionen algunos días (digamos que todas las entradas para ese día están agotadas), entonces podemos aplicar esta opción y deshabilitar los días para que el usuario los seleccione. beforeShowDay ejecuta una función pasando cada día como parámetro. Usaremos el enlace CDN en el código para agregar diferentes bibliotecas y estilos. Para mostrar esta función como cualquier otro widget de jQuery UI, tenemos que vincularnos a jQuery y jQuery UI. Copie este código dentro de su archivo HTML para vincular nuestro archivo a jquery y jquery UI a través de CDN (Red de entrega de contenido). Aquí hemos usado el CDN de google pero también puedes usar jquery o el CDN de Microsoft

<enlace href=’https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css’rel=’hoja de estilo’>

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js”></script>

<script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js”></script>

Vamos a crear una array en javascript con elementos de días que no están disponibles. A continuación, los códigos 9/12/2019 y 13/12/2019 no están disponibles, mientras que las fechas restantes sí lo están. Hemos usado la función beforeShowDay:my_check para ejecutar el código javascript para devolver True o False según las fechas mencionadas en la array. Antes de mostrar el calendario, cada día se pasa a través de esta función y, según el valor de retorno, se muestra la fecha.

Ejemplo 1:

<!DOCTYPE html>
<html>
<head>
    <link href=
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' 
         rel='stylesheet'>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
    </script>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
          
    </script>
    <style>
        h1{
            color:green;
        }
        .ui-datepicker {
            width: 12em;
        }
  
          
  
    </style>
</head>
  
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h4>jQuery UI beforeShowDay</h4>
    Start Date:
    <input type="text" id="my_date_picker1">
    <script>
        $(document).ready(function() {
            ////////
            $(function() {
                $("#my_date_picker1").datepicker({
                    dateFormat: 'dd-mm-yy',
                    defaultDate: "02-12-2019",
                    beforeShowDay: my_check
  
                });
            });
  
            function my_check(in_date) {
                in_date = in_date.getDate() + '/'
                + (in_date.getMonth() + 1) + '/' + in_date.getFullYear();
                var my_array = new Array('9/12/2019', '13/12/2019');
                //$('#d1').append(in_date+'<br>')
                if (my_array.indexOf(in_date) >= 0) {
                    return [false, "notav", 'Not Available'];
                } else {
                    return [true, "av", "available"];
                }
            }
        })
    </script>
  
</body>
</html>

Producción:

Bloqueo de un día en particular: Podemos optar por bloquear un día de la semana en particular en el calendario. Lo que deshabilitará el día de la semana de forma permanente y hará que no esté disponible para la selección de ninguna semana. A lo largo del calendario. En el siguiente ejemplo, hemos elegido deshabilitar el domingo .

Ejemplo 2:

<!DOCTYPE html>
<html>
  
<head>
    <link href=
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css'
          rel='stylesheet'>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
    </script>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
    </script>
    <style>
        h1 {
            color: green;
        }
          
        .ui-datepicker {
            width: 12em;
        }
    </style>
</head>
  
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h4>jQuery UI beforeShowDay</h4> Start Date:
        <input type="text" id="my_date_picker1">
        <script>
            $(document).ready(function() {
                $(function() {
                    $("#my_date_picker1").datepicker({
                        dateFormat: 'dd-mm-yy',
                        beforeShowDay: my_check
                    });
                });
  
                function my_check(in_date) {
                    if (in_date.getDay() == 0) {
                        return [false, "notav", 'Not Available'];
                    } else {
                        return [true, "av", "available"];
                    }
                }
            })
        </script>
   </center>
</body>
  
</html>

Producción:

Filtraciones más complejas: ahora intentaremos filtrar todos los segundos sábados junto con todos los domingos. Podemos hacer esto usando el siguiente código.
Identificación de segundos sábados Aquí está la lógica detrás de la identificación de un segundo sábado en cualquier mes dado. En primer lugar, identificamos el primer día del mes y su día de la semana (el domingo es 0, el lunes es 1 y así sucesivamente…) 14-(El número de día de la semana del primer día del mes) nos da la fecha del 2º sábado de el mes. Se ha utilizado una lógica similar en el siguiente código.

Ejemplo 3:

<!DOCTYPE html>
<html>
<head>
    <link href=
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' 
          rel='stylesheet'>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
    </script>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
    </script>
    <style>
        h1 {
            color: green;
        }
          
        .ui-datepicker {
            width: 12em;
        }
    </style>
</head>
  
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h4>jQuery UI beforeShowDay</h4> Start Date:
        <input type="text" id="my_date_picker1">
        <div id=d1></div>
        <script>
            $(document).ready(function() {
                $(function() {
                    $("#my_date_picker1").datepicker({
                        dateFormat: 'dd-mm-yy',
                        beforeShowDay: my_check
                    });
                });
  
                function my_check(in_date) {
                    var firstDay = new Date(in_date.getFullYear(), 
                                               in_date.getMonth(), 1);
                    var saturday2 = 14 - firstDay.getDay()
                    if (in_date.getDay() == 0 || 
                                      in_date.getDate() == saturday2) {
                        return [false, "notav", 'Not Available'];
                    } else {
                        return [true, "av", "available"];
                    }
                }
  
            })
        </script>
    </center>
</body>
  
</html>

Producción:

Del mismo modo, podemos deshabilitar los sábados 2 y 4 también. Aquí está el código para deshabilitar el domingo, el segundo sábado y el cuarto sábado.

function my_check(in_date) {
            var firstDay = new Date(in_date.getFullYear(), in_date.getMonth(), 1);
            var saturday2 = 14 - firstDay.getDay()
            var saturday4 = 28 - firstDay.getDay()
            if (in_date.getDay() == 0 || in_date.getDate() == saturday2 
                                      || in_date.getDate() == saturday4) {
                return [false, "notav", 'Not Available'];
            } else {
                return [true, "av", "available"];
            }

Publicación traducida automáticamente

Artículo escrito por mayeshmohapatra y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *