kile
kile

Reputation: 152

Replacing div content with an external file from within an external file loaded in said div

I have a file, say 'file1.html', loaded into a div via jQuery $('#info').load('info/file1.html'); I want to change the content of #info from within file1 so file1.html looks like this:

<a href="#" onclick="loadFile(this.value);" value="file2">File2</a>

where

function loadFile(f) {
    $('#info').load('info/'+f+'.html');
}

However, I only get a blank page in the div after the click. I also tried removing the 'info/' if the folder setup broke it but nothing. What's wrong?

Upvotes: 1

Views: 852

Answers (2)

Ben Lee
Ben Lee

Reputation: 53319

The problem is that anchor tag dom objects (HTMLAnchorElement) don't have a "value" property set on them. To get at the value attribute of the anchor tag that the dom object represents, you can do $(this).attr('value') (instead of this.value, which will just be undefined).

But really, you should be attaching your event using an id/class and jquery, not by using an onclick attribute. And you should be calling your anchor attribute data-value, not value, to conform to HTML5 specs on custom attributes. So the better way to do this would be:

HTML:

<a href="#" id="file-loader" data-value="file2">File2</a>

Javascript:

$('#file-loader').click(function(ev) {
    $('#info').load('info/' + $(this).attr('data-value') + '.html');
    ev.preventDefault();
});

Upvotes: 3

Victor
Victor

Reputation: 5769

Use:

  <a href="#" onclick="loadFile('file2');">File2</a>

Upvotes: 0

Related Questions