Julius'Lab

agosto 2023

(Formidable,Javascript) Checkboxes de Dynamic Fields – Aplicar JS para contar y limitar checkboxes

Formidable tiene un par de códigos en JS que cuentan y limitan las Checkboxes de un Checkbox field:

Count number of checked boxes:

Limit the number of checked boxes

 
Estos códigos funcionan muy bien con los campos Checkbox nativos de Formidable,pero no funcionan con los checkboxes creados por un Dynamic field.

Para esto, ChatGPT me ayudó a adaptar los scripts para que funcionen con los Dynamic/Checkboxes fields:

Limita los checkboxes seleccionados a un número arbitrario (en este caso 3):

jQuery(document).ready(function($) {
    var limit = 3; // Change this to your desired limit
    // Use event delegation to handle dynamic checkboxes
    $(document).on('change', 'input[name="item_meta[973][]"]', function() {
        var checkbox_num = $('input[name="item_meta[973][]"]:checked').length;
        if (checkbox_num > limit) {
            this.checked = false;
        }
    });
});

Cambiar 973 al ID del Dynamic/checkboxes field.

Cuenta los checkboxes seleccionados y coloca el valor en cualquier lugar:

jQuery(document).ready(function($) {
    // Use event delegation to handle dynamic checkboxes
    $(document).on('change', 'input[name="item_meta[973][]"]', function() {
        var val1 = $('input[name="item_meta[973][]"]:checked').length;
        $("#field_checkLimit").val(val1);
    });
});

Cambiar 973 al ID del Dynamic/checkboxes field, y dar nombre de class checkLimit a cualquier contenedor (div, span, etc.) en el que quiera colocarse el número de checkboxes seleccionadas.

Este es el script de los dos códigos combinados, para que lo haga todo junto:

jQuery(document).ready(function($) {
    var limit = 3; // Change this to your desired limit
    $(document).on('change', 'input[name="item_meta[973][]"]', function() {
        // Limit the number of checked checkboxes
        var checkbox_num = $('input[name="item_meta[973][]"]:checked').length;
        if (checkbox_num > limit) {
            this.checked = false;
        }

        // Count checked checkboxes
        var val1 = $('input[name="item_meta[973][]"]:checked').length;
        $("#field_checkLimit").val(val1);
    });
});

(Formidable,Javascript) Checkboxes de Dynamic Fields – Aplicar JS para contar y limitar checkboxes Leer más »