Atma
Atma

Reputation: 29767

how to not reload when loading ajax modal

I am putting a modal alert on the screen when a user clicks a choice of a dropdown like this:

$(document).ready(function(){

    $('#id_state').change(function(e){
        var selection = $("#id_state").val();
        if(selection == 1){
            event.preventDefault(); 
            var entryType = 'diabetes';
            var data = new Object();
            data.entryType = entryType;
            programAlertModal(programAlertModalCallback, data); 

            return false; 

        }
     });

     $('#id_state').trigger('change');
});

Program alert modal is then called here:

programAlertModal:function(callback, data){
            var entryType = data.entryType;
            var url = '/shared/enrollment/'+entryType+'/';

            $.get(url, function(result) {  
                callback(result, entryType); 

                return false;
            });
        },

        programAlertModalCallback:function(result, entryType){  
            $( "body" ).append(result);

        },

The result is some html that looks like this:

<div class="takeover">
  <div class="takeover-bg"></div>
  <div class="takeover-body">
  {% if entry_type == 'diabetes' %}
    <h1>My awesome title</h1>

    <a href="">Dismiss</a>
  </div>
</div>

How can I dismiss what is loaded without reloading the page (and clearing the dropdown selection)?

Upvotes: 0

Views: 43

Answers (2)

Carlos Calla
Carlos Calla

Reputation: 6706

Pass an e parameter to your function and add e.preventDefault(); to prevent the default behaviour of the a tag that reloads the page. You should also include href="#" in your a since leaving it blank causes some trouble in some cases.

Upvotes: 1

tcooc
tcooc

Reputation: 21209

Add a class to the Dismiss link so we can reference it:

<a href="#" class="dismiss">Dismiss</a>

Then bind a handler that removes the modal in the callback:

programAlertModalCallback: function(result, entryType) {
  var $result = $(result).appendTo("body");
  $result.find("a.dismiss").on("click", function(e) {
    e.preventDefault();
    $result.remove();
  });
},

Upvotes: 1

Related Questions