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());
});
}
});
}