Failed to using jQuery in loaded script

Discussions about Forms Designer for SharePoint 2013 / 2016 and Office 365.
Locked
User avatar
Anton Vityaz
Posts: 7
Joined: Mon Jun 22, 2015

22 Jun 2015

I've add code to load script on the SPForm button OnClick:

$.getScript("somescript.js", function(,,)

{

callMethodFromTheScript();

}

I've use callMethodFromTheScript() from the script library.

Calling this way I have got and error inside callMethodFromTheScript() - "$ is undefined".

How I can correctly import custom script function wich also uses jQuery $ functions?

User avatar
rostislav
Moderator
Posts: 364
Joined: Mon Oct 19, 2015

24 Jun 2015

You'll need to define $ and JQuery variables globally, like so:

Code: Select all

window.$ = $;
window.JQuery = $;

//then you can do your stuff
$.getScript("/script.js", function(data, textStatus, jqxhr)
{
    callMethodFromTheScript();
})

User avatar
Anton Vityaz
Posts: 7
Joined: Mon Jun 22, 2015

24 Jun 2015

Thank you! Works perfect!

User avatar
Евгений Минчев
Posts: 6
Joined: Fri Jul 10, 2015

10 Jul 2015

Hi. It works perfect only for javascript library.

For JQuery library functions like:

(function($) {

$.fn.testFunc = function(options) {

});

}(jQuery));

It's not working.

Could you help me with this issue.

Tnx.

User avatar
rostislav
Moderator
Posts: 364
Joined: Mon Oct 19, 2015

13 Jul 2015

The reason it doesn't work (two reasons, actually):
-you have a problem with brackets
-above we've defined JQuery, not jQuery (as we should have)

Correct version of your code:

Code: Select all

...
window.jQuery = $;
...

//in your script:
(function($) {
  $.fn.testFunc = function(options) {
  }
})(jQuery);

User avatar
Евгений Минчев
Posts: 6
Joined: Fri Jul 10, 2015

20 Jul 2015

Unfortunately it's noy working.

For example i tried to use datatable grid plugin for prettefy standart grid in form.

But it has be shown for me like TypeError: $(...).dataTable is not a function

my code is


window.$ = $;

window.JQuery = $;

$.getScript("js/jquery.dataTables.min.js", function(data, textStatus, jqxhr){});

$('table').dataTable();


Any ideas?

User avatar
Евгений Минчев
Posts: 6
Joined: Fri Jul 10, 2015

20 Jul 2015

for mor information - DataTable plugin

User avatar
rostislav
Moderator
Posts: 364
Joined: Mon Oct 19, 2015

20 Jul 2015

So, as I've posted above, you need to change JQuery to jQuery. Also, your function needs to be inside the success function. Try this code:

Code: Select all

window.$ = $;
window.jQuery = $;
$.getScript("js/jquery.dataTables.min.js", function(data, textStatus, jqxhr){
    $('table').DataTable();
});

Locked
  • Information
  • Who is online

    Users browsing this forum: No registered users and 15 guests