vendredi 2 septembre 2016

How to replace an value in an array with checkboxes jQuery

Im trying to arrange a checkbox array with jQuery. I have managed to get the values to add to the array in order and remove the correct one, but for the life of me i cannot get it to replace the removed value with the newly selected value. Currently it just adds the new value to the end of the array.

Heres my code so far:-

var array = [];
        $('input[type="checkbox"]').click(function () {
            if ($(this).attr('checked')) {
                // Add the new element if checked:
                array.push($(this).attr('value'));
                $('#ff_elem512').val(array);
            }
            else {
                // Remove the element if unchecked:
                for (var i = 0; i < array.length; i++) {
                    if (array[i] == $(this).attr('value')) {
                        array.splice(i, 1);
                        $('#ff_elem512').val(array);
                    }
                }
            }

            console.log(array);
        });

Thanks in advanced!!




Aucun commentaire:

Enregistrer un commentaire