views:

31

answers:

2

languages used: html, javascript/jquery, and php 5.2

So I created this function that onclick creates a "group". For simplicity, we'll say this is a group (aka the response from ajax.):

<div id="group1">Group #1</div>

This is where the groups go: (html page)

<div id="groups">
    <!-- groups go here -->
</div>

So the user creates group #1. No problem. The response is returned and Group 1 appears on the screen where it should.

The problem I run into is when the user creates group #2.

success:function(data){
                    $('#groups').prepend().html($.trim(data));
                }

The above script is what assigns the new group to the div. The trouble is, instead of prepend group2 before group1, group2 replaces group1. (not good)

I'm not exactly sure what is happening but when the user creates a 2nd group the script looks for a child element of group to prepend the script finds none so it replaces group1.

If I go to view source I do not see the div for group1 or two but I can visually see the response on my screen.

What is going on here and how do i fix it?

Thanks!

+2  A: 

If your response is HTML, you can do it like

$("#groups").prepend(data);
//or
$(data).prependTo($("#groups"));

What you're doing is prepend()ing nothing, and then setting #groups' html to the data

Simen Echholt
Confirmed, appears to be working! I had it stuck in my head that the prepend function was giving the location of where to put the html().Thanks Simen.
payling
+1  A: 

You should be passing the content as a parameter to prepend, like this:

$('#groups').prepend($.trim(data));

Calling html afterwards will simply replace the contents of #groups.

Also, this content is generated dynamically, so you won't be able to see it if you view the source of the page. If you want to see such things, consider installing Firebug - it lets you view dynamic content, debug scripts and much more.

casablanca
Thanks for the tip - firebug, I'll give it a go.
payling