0

Using ajax and jQuery, I'm trying to load content from a specific element in an external document when a user toggles a switch. The target content is dictated by the toggle switch element's name.

So I start with HTML...

<input id="toggle1" name="externalContent1" class="toggle" type="checkbox">
<input id="toggle2" name="externalContent2" class="toggle" type="checkbox">
<input id="toggle3" name="externalContent3" class="toggle" type="checkbox">

I first tried to use '.load()'...

$('.toggle').click(function () {

  var section = '#' + $(this).attr('name');

  if ($(this).is(':checked')) {
    $('#target').load("content.htm " + section);
  }

  else {
    $(section).remove();
  }
});

This works, but it replaces the content of the #target element. I need to append rather than replace.

So then I tried a few suggestions from other SO questions using .get()

if ($(this).is(':checked')) {
  var content;
  $.get('content.htm ' + section, function(data) {
    content = data;
    $('#target').append(content);
  });
}

But these solutions using .get(), .post(), and .ajax() (at least in the way I've tried), don't allow me to specify an element in content.htm, it just pulls the whole document.

Is there a way to use .get() to retrieve a specific element from an external document?

As I've been thinking this through, I suppose I could also search the retrieved page for the section, and only append that. I found this suggestion, and tried it, but I'm not having any luck with this either:

if ($(this).is(':checked')) {
  $.ajax({
    url: 'content.htm',
    type: 'GET',
    success: function(res) {
      $(res.responseText).find(section).each(function(){
        $('#target').append($(this).html());
      });
    }
  });
}
Community
  • 1
  • 1
Jesse Schoff
  • 750
  • 9
  • 24

1 Answers1

1

With a bit of hacking, you can use the .load() solution. First load into a separate element, then append.

if ($(this).is(':checked')) {
    $('<div id="tempForLoad">').load("content.htm " + section, function(){
        $('#target').append($('#tempForLoad').html());
        $('#tempForLoad').remove();
    });
 }
Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • Thanks, that works. I guess a 'hacky' solution will have to do. You're missing a `)` in the line `($('#tempForLoad').remove();` Speaking of that line, why is it wrapped in an extra set of parenthesis? I'm going to give this another day to see if anyone has any other suggestions before marking yours as the answer. – Jesse Schoff Sep 23 '14 at 20:01
  • The open parenthesis was a typo, fixed. That's certainly fine to wait. :) – Scimonster Sep 23 '14 at 20:06