jQuery append html x-amount of times

Hi everyone,

how do I go about appending some HTML to the same selection x-amount of times? For example, I might want to append a paragraph 3 times to the same div.

So I’d have:

<p id="computer" name="computer">hi there<p>
<p id="computer" name="computer">hi there<p>
<p id="computer" name="computer">hi there<p>

I’m using a select menu with numbered options from 0-6. When someone selects option 3, 3 instances of the same paragraph should be appended to the selection. If 5 is selected, 5 paragraphs would be appended. What I’d also like is for the name attribute to be incremented with a number.

So I’d have:

<p id="computer" name="computer[0]">hi there<p>
<p id="computer" name="computer[1]">hi there<p>
<p id="computer" name="computer[2]">hi there<p>

<script>
      $(document).ready(function() {

        $("#selectmenu").on('change', function () {
        $("#content").append().html('<p id="computer" name="computer">hi there<p>');
        }
        );
      });
    </script>

I’ll probably have to include a loop somewhere?

Please assist me with this.

Thank you. :slight_smile:

Hi RedBishop,

Indeed, you can do this with a for loop.

var content = $("#content");

$("#selectmenu").on('change', function () {
    var count = $(this).val();
    for (var i = 0; i < count; i++)
    {
        content.append("<p id=\\"computer\\" name=\\"computer[" + i + "]\\">hi there<p>");
    }
});

Hi fretburner,

thank you for helping me!

The code works as expected but after playing around with it I realize that my choice of append was definitely not the best option. If option 3 is selected 3 paragraphs are created. If option 5 is then selected there should be a total of 5 paragraphs and not 8 paragraphs. Thus option 1 only displays 1 paragraph, option 2 = 2 paragraphs, option 3 = 3 paragraphs etc. The name attribute would also be incremented from the beginning again. The name attribute for option 1’s paragraph would be: name=“computer[0]”; for option 3 the first paragraph would have name=“computer[0]”, while the third paragraph would be name=“computer[2]” etc…

Do you think it would be a big mission to change the previous code?

Thank you and I hope you’re well.

Hi RedBishop,

Nah, not really.

Just build up a string, then replace the HTML of the content div with the newly created string, like so:

var content = $("#content");
 
$("#selectmenu").on('change', function () {
    var count = $(this).val(),
        newContent = "";
    for (var i = 0; i < count; i++)
    {
        newContent += "<p id=\\"computer\\" name=\\"computer[" + i + "]\\">hi there<p>";
    }

    content.html(newContent);
});

Nah, not really.

Well for certain people it might be a big mission…:smiley:

Thanks Pullo, very nice indeed. This is what I was looking for.

I think I’ve had enough for one day, G’night and thanks to you & fretburner for the help

Hi Pullo,

how are you this morning?

Do you think the following would work? I’m trying to retrieve the select menu’s name and then for each paragraph created, I have another paragraph with the name of the select menu.

I can use var name = $(“#selectmenu”).attr(“name”); to retrieve the name, but how to “echo it out”?

<p>Amy store 1<p><p>hi there</p>
<p>Amy store 2<p><p>hi there</p>
<p>Amy store 3<p><p>hi there</p>

Thank you!

Good morning,

Fine thanks :slight_smile:

Something like this?

var content = $("#content");
 
$("#selectmenu").on('change', function () {
    var count = $(this).val(),
        newContent = "",
        name = $(this).attr("name");

    for (var i = 0; i < count; i++)
    {
        newContent += "<p id=\\"computer\\" name=\\"computer[" + i + "]\\">hi there<p><p>Created by menu: " + name + "</p>";
    }

    content.html(newContent);
});

Brilliant, thanks Pullo.

I’ve changed :

" + name + "

to

" + name + (i+1) +"

in order to increment the number from 1. Seems to work fine.

Yup, that’s the way to go :slight_smile:

Hi again Pullo,

I’ve added the jQuery to my actual page and a number of “issues” have surfaced. The names of my select menus are of the format: name=“somename[somename]”. Do you know of a technique whereby name = $(this).attr(“name”); only retrieves the content between the brackets?

Another problem is that I have multiple select menus on my page each with the same class=“someclass”. If I select an option from a random select menu, all of the other occurrences of class=“content” get the same paragraphs. I’m sure you know what I mean. This is probably solved by sticking next() somewhere?

I appreciate all of your help - thank you.

Hi there,

var name = $(this).attr("name"),
    matches = /\\[(.*)\\]/.exec(name);
console.log(matches[1]);

In your previous example you were appending to a div with the id content.
If you want to use a class, we’ll need to see the HTML so that the correct selector can be found.

Thank you for getting back to me. :slight_smile: I’ve changed the IDs to classes. The generated HTML would look like this:

<select class="selectmenu" name="computer[bob]" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p class="content"></p>


<select class="selectmenu" name="computer[chris]" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<p class="content"></p>

<select class="selectmenu" name="computer[mike]" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p class="content"></p>

var name = $(this).attr(“name”),
matches = /\[(.*)\]/.exec(name);
console.log(matches[1]);

Thank you will try that out.

If the p element you want to append the content to is directly after the select element, then you were right on the money:

$(this).next().html(newContent);

:slight_smile:

$(this).next().html(newContent);

Great, it is working well now, thank you very much. One thing that I still have a problem with is the regular expression. Must I substitute ‘name’ with ‘matches’ in the ‘Created by menu’ paragraph? And must I leave console.log in the script?

Thanks!

var content = $(".content");

$(".selectmenu").on('change', function () {
    var count = $(this).val(),
    newContent = "",
    var name = $(this).attr("name");
    matches = /\\[(.*)\\]/.exec(name);
     console.log(matches[1]);

    for (var i = 0; i < count; i++)
    {
        newContent += "<p id=\\"computer\\" name=\\"computer[" + i + "]\\">hi there<p><p>Created by menu: " + name + "</p>";
    }

    $(this).next().html(newContent);
});

No and no, in that order:

var content = $(".content");
 
$(".selectmenu").on('change', function () {
    var count = $(this).val(),
        newContent = "",
        nameWithBrackets = $(this).attr("name");
        name = /\\[(.*)\\]/.exec(nameWithBrackets)[1];

    for (var i = 0; i < count; i++)
    {
        newContent += "<p id=\\"computer\\" name=\\"computer[" + i + "]\\">hi there<p><p>Created by menu: " + name + "</p>";
    }

    $(this).next().html(newContent);  
});

That should do you :slight_smile:

That’s sorted then :tup:

Thank you so much for all of your assistance. You’ve been a huge help :slight_smile:

Hope you have a good night!

Hi Pullo,

how are you?

I promise I won’t take up a lot of your time today, but I have a quick query if you don’t mind too much.

As you know I have multiple select menus on the page, which I have “looped out” with a while loop. For each select menu I’m also returning some other info:
$num_computers = $row[‘num_computers’];

So depending on how many select menus there are, I’ll have an equal number of $num_computers, each with a different value (1, 5, 6) etc.

I know I can use
var count = $(this).val(), to get the specific value of the specific select menu option, but how to get the associated $num_computers value?

Using
var computer = ‘<?php echo $num_computers;?>’; only retrieves the last $num_computers on the page.

I hope all of this makes somewhat sense!

Thank you in advance.

Hi Red Bishop,

Sorry I didn’t respond sooner, the email notifications have slowed to a crawl for some reason and I missed this.

$num_computers looks like a PHP variable.
Where are you storing it?
If you need to associate this variable with each select element, you might consider storing it as a data attribute on each element.
You would do this in your while loop e.g.

echo "<select data-computers='" + $num_computers +"'>"

You can then reference this in the JS, like so:

$(".selectmenu").on('change', function () {
  alert($(this).data("computers"));
  ...
});

Hey Pullo,

no need to apologize! I’m grateful for any assistance.

$num_computers looks like a PHP variable.
Where are you storing it?

In the while loop I’m assigning each store’s $row[‘num_computers’]; to $num_computers, which I then echo out. But instead of echoing it out I’m now trying to use it to create another select menu with numbered options. If a specific $num_computers has a value of 5, it would create a select menu with numbered options from 0-5.

If you need to associate this variable with each select element, you might consider storing it as a data attribute on each element.

I’m using HTML4, so this probably won’t work. I got the second select menu working but it’s not retrieving the specific $num_computers value.

var computer = '<?php echo $num_computers;?>';

only returns the last $num_computers value. Don’t know what to do.

Thank you.

So that’s PHP, right?

Once you have a reference to $num_computers for the individual stores, couldn’t you just use it to create a for loop?

echo "<select>";
for ($x=0; $x<=$num_computers; $x++){
  echo "<option value=" . $x . ">Computer no. " .$x . "</option>";
} 
echo "</select>";

Or did I miss something (also likely :))