pawel
pawel

Reputation: 6136

How to make jquery load() in external javascript function?

i'm trying to create my own tool in javascript, which will help me load some php functions/files into my div.

Here is my javascript:

$(document).ready(function () {
    $('.btn').click(function() {        
        $('#someid').testit();
        //   $('#someid').load('somefile');  it works
        return false;
    })   
});

function testit() { 
    $(this).load('somefile');
}

And my html:

<div id="someid"></div>
<form>
    <input type="submit" value="test" class="btn" />
</form>

I can't load the resource from external function - why is that?

Upvotes: 1

Views: 364

Answers (4)

jfriend00
jfriend00

Reputation: 707486

If you want to call something like:

$('#someid').testit();

Then, you have to create a jQuery plugin that defines the method testit. That code would look something like this:

jQuery.fn.testit = function() {
    return this.load('somefile');
}

Then, and only then can you use testit() as a jQuery method like this:

$('#someid').testit();

And, it will operate on the desired selector.

Here's some of the jQuery doc on writing plugin methods like this.

Upvotes: 2

RichH
RichH

Reputation: 6138

You can pass the element like this ...

$(document).ready(function () {
    $('.btn').click(function() {        
        testit($('#someid'));
        return false;
    })   
});

function testit(el) { 
    el.load('somefile');
}

Or create a JQuery plugin as jfriend00 mentions

Upvotes: 1

Owen
Owen

Reputation: 501

Unfortunately you can't chain functions like that out of the box, you'd have to put it into the jquery.fn prototype to make a plugin.

What you could do instead is use the .each() function on the selector to call your function.

In your case, if you were to call $("#someid").each(testit); jquery will then call the testit() function on each of the elements found.

Upvotes: 1

xdazz
xdazz

Reputation: 160863

You need to do like below:

$.fn.testit = function () {
  return this.load('somefile');
}

Upvotes: 2

Related Questions