user2810718 user2810718 - 2 months ago 12
jQuery Question

Function cannot be called in $(document).ready(function() {

I have a function(modal confirmation) defined in an external js file which returns a value as such :

function confirmation(question) {
var defer = $.Deferred();
$('<div></div>').html(question).dialog({
autoOpen: true,
modal: true,
title: 'Confirmation',
buttons: {
"Delete All Items": function() {
defer.resolve("true"); //this text 'true' can be anything. But for this usage, it should be true or false.
$(this).dialog("close");
},
"Cancel": function() {
defer.resolve("false"); //this text 'false' can be anything. But for this usage, it should be true or false.
$(this).dialog("close");
}
},
close: function() {
//$(this).remove();
$(this).dialog('destroy').remove()
}
});
}





Now when I try to call the function inside the
$(document).ready(function() {
; I get an Uncaught Reference Error.

All the necessary files have been included in calling script. I would like to understand why is this and how i can solve the issue?

MJH MJH
Answer

Except for the missing curly-brace at the end, and assuming your "necessary files" include jquery-ui, there doesn't seem to be anything wrong with your function. See this jsfiddle, which does not generate any error.

Perhaps the problem is elsewhere in your code? It may help if you can post a Minimal, Complete, and Verifiable example.

References:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.theme.css" />

Script:

$(document).ready(function() {
  confirmation("What's all this, then?");
});

function confirmation(question) {
    var defer = $.Deferred();
    $('<div></div>').html(question).dialog({
      autoOpen: true,
      modal: true,
      title: 'Confirmation',
      buttons: {
        "Delete All Items": function() {
          defer.resolve("true"); //this text 'true' can be anything. But for this usage, it should be true or false.
          $(this).dialog("close");
        },
        "Cancel": function() {
          defer.resolve("false"); //this text 'false' can be anything. But for this usage, it should be true or false.
          $(this).dialog("close");
        }
      },
      close: function() {
        //$(this).remove();
        $(this).dialog('destroy').remove()
      }
    });
}
Comments