Search code examples
jqueryspring-bootbootstrap-modaladminlte

Bootstrap modal does not update content and reset form in adminlte


When i open modal with data and close it and open again, form does not reset and show old data how can i fix it and initialize form data?

I use bootstrap v3.3.7 and adminlte v2

modal html:

<div class="modal fade" id="new" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-body">
                <img src="/image/loading.gif" class="loading"/>
                <span>Lodaing . . .</span>
            </div>
        </div>
    </div>
</div>

click on button:

<button href="/edit/id" data-target="#new" data-toggle="modal" type="button" class="btn btn-success">Edit</button>

open modal content with spring boot cotroller:

@RequestMapping(value =  "/edit")
public String edit(Model model,
                   @ModelAttribute(value = "id") String paramId){


    if (paramId == 0){
        //open modal without data...
    }

    if (paramId != 0){
        //open modal with data...
    }


    model.addAttribute("edit", data);

    return "view/edit"; //open modal html template

}

Solution

  • It's obvious that your modal content remain on each time you open and close your modal, You should clear your modal content with the following code:

    $(document).on('hidden.bs.modal', '.modal', function (e) {
        $(this).find(".modal-content").empty();
        $(this).removeData('bs.modal');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    
    <button href="/edit/id" data-target="#new" data-toggle="modal" type="button" class="btn btn-success">Edit</button>
    <div class="modal fade" id="new" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-body">
                    <img src="/image/loading.gif" class="loading"/>
                    <span>Lodaing . . .</span>
                </div>
            </div>
        </div>
    </div>