Search code examples
javascriptjqueryarraysjquery-loadjquery-append

Append and Load from an array


I'm pretty new to javascript and jQuery in general and I've been working on this script for about 3 days now. I searched around for a solution to this but wasn't able to find it yet. I guess my search skills suck.

So, I'm trying to load an element by from multiple pages and append them to an existing DIV. For example, I have a page called test.php which has <div id="container"> in it. I also have multiple other pages called:

  • pizzas.php
  • pies.php
  • apples.php
  • oranges.php
  • mangos.php
  • etc

These are the pages that I'll be pulling data from to load into test.php. Each of the listed pages has <div id="about"> somewhere in it.

Users will send me a string of pages that they'd like to load from through a text field they fill out. I take that and split it. Using that array, I'd like to create some DIV's for each string in that array. So this is where I'm at so far, assuming a user who has requested info from pizzas, pies, and apples:

<script>
var str = "pizzas,pies,apples";
var test = str.split(",");

$.each(test, function(i,v){
  $('#container').append('<div id="' + v + '"></div>');
});

</script>

Which yields:

<div id="container">
  <div id="pizzas"></div>
  <div id="pies"></div>
  <div id="apples"></div>
</div>

After creating the new DIV's, I want to load #about from each page into its corresponding DIV. I thought I could do it by adding this to the each loop, but it doesn't work:

$( '"#' + v + '"' ).load( "index.php?x=" + v + " #about" );
//like $("#pizzas").load('index.php?x=pizzas #about');

And that's where I get stuck. Anyway, I'd greatly appreciate any help I could get on this.


Solution

  • It looks like you can just use something like this after you've created the divs:

    $("#container > div").each(function() {
        $(this).load("index.php?x=" + this.id + " #about");
    });
    

    Or, just do in in one shot like this:

    var str = "pizzas,pies,apples";
    var test = str.split(",");
    
    var container = $('#container');
    $.each(test, function(i,v){
        $("<div></div>", {id: v}).appendTo(container)
            .load("index.php?x=" + v + " #about");
    });