How to NOT show a modal again after a button is clicked/accepted/confirmed?

眉间皱痕 提交于 2019-12-13 07:18:09

问题


I have a bootstrap modal showing up that needs to be confirmed/accepted/clicked (button: #id_complete) in order to access the page. In order to activate the button the user needs to click two check boxes. The goal is: I want to have the modal to show up only until the #id_complete button IS NOT clicked/confirmed/accepted yet in the session. If the button is clicked/confirmed/accepted the modal shouldn't show up again. The cookie should be valid for 1 day. I'm using jquery-cookie-1.4.0

The below example only shows up on the first sites visit though, which is not the goal.

<button id="id_complete" type="button" class="btn btn-default" data-dismiss="modal" disabled="disabled">I Accept!</button>

if ($.cookie('pop') == null) {
     $('#myModal').modal({
            backdrop: 'static'
         });
     $.cookie('pop', '1');
 } 

 $('#accepted1,#accepted2').click(function () {
    if ($('#accepted1:checked,#accepted2:checked').length == 2)
        $('#id_complete').removeAttr('disabled');
    else
        $('#id_complete').attr('disabled','disabled');
});

回答1:


Calling the modal function won't pause JavaScript execution which means the cookie will be set immediately.

To make the cookie expire after a day add an object with the expires property set 1.

Listen for the hidden.bs.modal or the hidden event on the modal depending on which version of bootstrap you have and then set the cookie:

// Bootstrap <2.3.2
if($.cookie('pop') == null) {
    $('#myModal').modal({
        backdrop: 'static'
    }).on('hidden', function(){
        $.cookie('pop', '1', {expires: 1});
    });
}
// Bootstrap 3
if($.cookie('pop') == null) {
    $('#myModal').modal({
        backdrop: 'static'
    }).on('hidden.bs.modal', function(){
        $.cookie('pop', '1', {expires: 1});
    });
}

To answer the question in the comments:

To make it expire after the page session you can use window.sessionStorage object and store when the modal was last accepted:

var lastAccepted = parseInt(sessionStorage.lastAccepted);
// If lastAccepted isn't a number (because it doesn't exist or some other reason)
// or the last acceptance was more than a day ago 
if(isNaN(lastAccepted) || Date.now() - lastAccepted > 86400000) {
    $('#myModal').modal({
        backdrop: 'static'
    }).on('hidden.bs.modal', function(){
        sessionStorage.lastAccepted = Date.now();
    });
}



回答2:


The line where you set the cookie needs moving the click handler of the button.

In it's current position if the cookie is not found it will be created regardless of what the user is doing



来源:https://stackoverflow.com/questions/36788441/how-to-not-show-a-modal-again-after-a-button-is-clicked-accepted-confirmed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!