jqueryonclickmodal-dialogbootstrap-modal

Bootstrap modal onclick before modal is run


I am using a bootstrap modal on my website, and I want to be able to set the text of the model while calling it

for this I planned to use the onclick function.

example:
when a user clicks the button "delete list" a modal pops up with the header that I set in that specific onclick function:

 function functionCalledByOnclick(){
   $("#modalHeader").html("<p>Are you sure you want to remove **?</p>");

however a button "save" could also be pressed, in which case the header should say something different.

But when I click one of these buttons the modal is shown before the function is run and therefore the header text is not set.

Can I use the onclick function to set the text in a modal? Or must I find another way?


Solution

  • With JQuery it's easier to use the onclick event like this. This way you only need to assign an id to each button, and it's a bit easier on the eyes too.

    $(document).ready( function () {
        var deleteText = "<p>Are you sure you want to remove **?</p>";
        var saveText = "<p>Do you want to save **?</p>";
    
        $("#deleteButton").click( function () {
            $("#modalHeader").html(deleteText);
            $("#modal").modal("show");
        });
    
        $("#saveButton").click( function () {
            $("#modalHeader").html(saveText);
            $("#modal").modal("show");
        });
    });
    

    You can of course shorten it down by erasing the variables, but this is more organised.