Why modal keeps variable saved when new open new modal

#1

Hi,
I fetch some data from database and show into a datatable, when I click on edit I open a modal window where I?ve got a form to edit the data. I get the data id and save it into a variable int this way

var km_building_unit_id = this.id;

The problem is when I close the modal and open a new one for a different data it does edit the current data and the previous as well unless I refresh the whole page before.

this is my code sorry is quite long, many thanks for your help

    var kmg_admin_edit_building_unit = function() {

        // Store table id into a variable
        var table = $('#kmg_admin_building_units_list');
        var form = $('#kmg_admin_edit_building_unit_form');
        var error = $('.alert-danger', form);
        var success = $('.alert-success', form);
        var warning = $('.alert-warning', form);

        // If user close modal then it shouldn't show previous messages when modal opened again
        $('#kmg_admin_edit_building_unit_modal').on('hidden.bs.modal', function () {
            // Remove all alert message and highlights
            $('.alert_custom').removeClass('alert-danger');
            $('.alert_custom').removeClass('alert-success');
            $('.alert_custom').removeClass('alert-warning');
            $('.has-error').removeClass('has-error');
            $('.alert_custom').removeAttr('style');
            // Remove jquery form validation from previous modal
            form.validate().resetForm();
            // Reset every field of the previous form so i can populate them with new values
            form.trigger("reset");
            // Reset also selectpicker input from previous modal
            $("#kmg_admin_edit_building_comune").val('default').selectpicker("refresh");
            // Hide form when close modal so I can show loader animation
            form.hide(); 

       
            
        });

        // Handle click on button edit bank account
        table.on('click', '.kmg_admin_edit_building_unit', function(e) {

            // Get building unit ID associated to the edit button

            var km_building_unit_id = this.id;

            // Show edit group bank account modal
            $("#kmg_admin_edit_building_unit_modal").modal("show");

            // Get building unit details and show them in the form imputs
            $.ajax({  
    
                method:"POST",  
                data:{
                    km_building_unit_id: km_building_unit_id,
                    ajax_action: 'kmg_admin_get_building_unit'
                },  
                dataType:"JSON", 

                beforeSend: function() {
                    // Show loader animation
                    $(".modal-loader").show();
                }, 

                success: function(response){ 

                    if(response.notice_code == KM_WARNING_CODE){

                        // Add class alert danger to the message
                        $('.alert_custom', $('.horizontal-form')).removeClass('alert-danger');
                        // Remove class alert warning if was left by previous validation
                        $('.alert_custom', $('.horizontal-form')).addClass('alert-warning').show();
                        // Remove class alert success if was left by previous validation
                        $('.alert_custom', $('.horizontal-form')).removeClass('alert-success');
                        // Show error message
                        $('#kmg_admin_edit_building_unit_message_modal').html(response.notice_message);

                    }

                    $('#kmg_admin_edit_building_type').val(response.km_building_unit_tipology);
                    $('#kmg_admin_edit_building_type').selectpicker('refresh'); 
                    $('#kmg_admin_edit_building_piano').val(response.km_building_unit_piano);
                    $('#kmg_admin_edit_building_scala').val(response.km_building_unit_scala);
                    $('#kmg_admin_edit_building_interno').val(response.km_building_unit_interno);
                    $('#kmg_admin_edit_building_metri').val(response.km_building_unit_metri);
                    $('#kmg_admin_edit_building_sezione').val(response.km_building_unit_sezione);
                    $('#kmg_admin_edit_building_foglio').val(response.km_building_unit_foglio);
                    $('#kmg_admin_edit_building_particella').val(response.km_building_unit_particella);
                    $('#kmg_admin_edit_building_subalterno').val(response.km_building_unit_subalterno);
                    $('#kmg_admin_edit_building_categoria').val(response.km_building_unit_categoria);
                    $('#kmg_admin_edit_building_classe').val(response.km_building_unit_classe);

                    $.ajax({

                        url: 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json',
                        dataType: 'JSON',

                        complete: function(){   
                            // Hide modal animation
                            $(".modal-loader").hide(); 
                            // Show the form after everything has loaded
                            form.show(); 
                        },

                        success: function(result) {

                            // Make sure we empty the dropdown field before populating it otherwise names are duplicated
                            $("#kmg_admin_edit_building_comune").empty();

                            var jsonData = JSON.stringify(result);

                            // Build dropdown list with comuni list form json
                            $.each(JSON.parse(jsonData), function (key, entry) {
                                $('#kmg_admin_edit_building_comune').append('<option value="' + entry.nome + '">' + entry.nome + '</option>');
                            });

                            $('#kmg_admin_edit_building_comune').selectpicker('refresh');

                            // Check if we have a comune stored in the database
                            if(response.km_building_unit_comune !== ""){

                                $('#kmg_admin_edit_building_comune').val(response.km_building_unit_comune);
                                $('#kmg_admin_edit_building_comune').selectpicker('refresh');
                            }

                            // Check if we have a codice catasto stored in the database
                            if(response.km_building_unit_catasto !== ""){
                                $('#kmg_admin_edit_building_catasto').val(response.km_building_unit_catasto);
                            }

                            // Catch comune name from dropdown list and populate input codice catasto
                            $(document).on('change', '#kmg_admin_edit_building_comune', function(){
                    
                                var nome_comune = $(this).val();

                                $.each(JSON.parse(jsonData), function (key, entry) {
                                    
                                    if (entry.nome == nome_comune){

                                        $('#kmg_admin_edit_building_catasto').val(entry.codiceCatastale);

                                    }

                                })

                            });

                        }

                    }); // Fine ajax comuni


                    $('#kmg_edit_building_unit_submit').click(function(e) {

                        // Prevent form to be submitted again on page reload
                        e.preventDefault();

                        // Ajax call to update the building unit
                        $.ajax({

                            type: 'POST',
                            // Serialize form data and add also the ajax action
                            data: $(form).serialize()+"&ajax_action=kmg_admin_edit_building_unit"+"&km_building_unit_id="+km_building_unit_id,
                            dataType: 'JSON',

                            success: function(response){

                                console.log(response);

                                if (response.notice_code == KM_ERROR_CODE) {

                                    // Hide modal so I can show sweetalert
                                    $("#kmg_admin_edit_building_unit_modal").modal("hide");

                                    // Reset every field of the previous form so i can populate them with new values
                                    form.trigger("reset");

                                    Swal.fire({
                                        title: response.notice_title,
                                        text: response.notice_message,
                                        type: response.notice_status
                                    });

                                }

                                if (response.notice_code == KM_SUCCESS_CODE) {

                                    // Hide modal so I can show sweetalert
                                    $("#kmg_admin_edit_building_unit_modal").modal("hide");

                                    // Reset every field of the previous form so i can populate them with new values
                                    form.trigger("reset");

                                     Swal.fire({
                                        title: response.notice_title,
                                        text: response.notice_message,
                                        type: response.notice_status
                                    });

                                    // Reload datatable to remove the row just deleted
                                    $('#kmg_admin_building_units_list').DataTable().ajax.reload();


                                }

                            }




                        });
                        


                    });
                 
 

                },

                error: function(jqXHR, exception) {

                    if (jqXHR.status === 0) {
                        notice_message = 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.';
                    } else if (jqXHR.status == 404) {
                        notice_message = 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.';
                    } else if (jqXHR.status == 500) {
                        notice_message = 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.';
                    } else if (exception === 'parsererror') {
                        notice_message = 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.';
                    } else if (exception === 'timeout') {
                        notice_message = 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.';
                    } else if (exception === 'abort') {
                        notice_message = 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.';
                    }

                    // Add class alert danger to the message
                    $('.alert_custom', $('.horizontal-form')).addClass('alert-danger').show();
                    // Remove class alert warning if was left by previous validation
                    $('.alert_custom', $('.horizontal-form')).removeClass('alert-warning');
                    // Remove class alert success if was left by previous validation
                    $('.alert_custom', $('.horizontal-form')).removeClass('alert-success');
                    // Show error message
                    $('#kmg_admin_edit_building_unit_message_modal').html(notice_message);

                } 

            }); 


        });

    }
#2

Hi @vincekaribusana, that variable will get declared anew each time you click the table; however your DOM modifications inside the modal won’t automagically get reset when you hide it. But you might restore the initial markup before showing the modal like so:

var $modal = $('#my-modal')
var modalMarkup = $modal.html()

// Later, when showing the modal:
$modal.html(modalMarkup).modal('show')

(I’d suggest to show the modal after you populated the fields though, not before.)

1 Like
#3

Hi @m3g4p0p thanks for your help. I’ve also managed it with attaching the id into a hidden s field :wink: