javascriptdjangoalertifyalertifyjs

how to use alertify js with django to confirm either ok or cancel


hi i need to use alert message when some wants delete a post ask her/him to delete or cancel

i tried this but this is a default alert browser

<button onclick="return confirm('are you sure you want to delete {{obj.title}}')" class="bt mx-auto"><a href="{% url 'posts:post-detail' obj.id %}"><img src="{% static 'icons/delete.svg' %}" alt=""></a></button>

i want to use this alert

alertify.prompt("are you sure you want to delete ", "{{obj.title}}",
  function(evt, value ){
alertify.success('Ok: ' + value);
  },
function(){
alertify.error('Cancel');
  });

alertify

but i'm not sure where should i put that script in the template ? i use it inside the button delete , replacing to confirm() but seems doesnt work thanks for helping ..


Solution

  • ...i want to ask the user when a user wants to remove a post ,( agree or disagree ) if selected agree(ok) then the post will be remove , if selected disagree (cancel) do nothing with the post

    In order to achieve the desired result you need to change a bit your html in order to pass the current element (refer: this keyword) and like reported in the examples section you can attach to the window object a function called showAlert:

    window.showAlert = function(msg, title, ele) {
        var that = ele;
        alertify.prompt(msg, title,
                function(evt, value){
                    ele.closest('div').remove();
                },
                function(){
                    // do nothing 
                });
    }
    

    And change your button to:

    <button onclick="return showAlert('are you sure you want to delete',  '{{obj.title}}')".....
    

    <script src="//cdn.jsdelivr.net/npm/alertifyjs@1.13.1/build/alertify.min.js"></script>
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs@1.13.1/build/css/alertify.rtl.min.css"/>
    <script type="text/javascript">
    window.showAlert = function(msg, title, ele) {
        var that = ele;
        alertify.prompt(msg, title,
                function(evt, value){
                    ele.closest('div').remove();
                },
                function(){
                    // do nothing
                });
    }
    </script>
    
    
    <div>
        <p> This is the first post</p>
        <button onclick="return showAlert('are you sure you want to delete',  'post n. 1', this)">Click Me</button>
    </div>
    
    <div>
        <p> This is the second post</p>
        <button onclick="return showAlert('are you sure you want to delete',  'post n. 2', this)">Click Me</button>
    </div>
    <div>
        <p> This is the third post</p>
        <button onclick="return showAlert('are you sure you want to delete',  'post n. 3', this)">Click Me</button>
    </div>