Andriy Khrystyanovich
Andriy Khrystyanovich

Reputation: 1452

jquery set text

I have some div

<div id="editCatalogListItemHideMe">
    <div class="listItem">
        <table class="sectionTable">
            <tr>
                <td class="sectionLeft">
                    <span id="numberLabel"></span><span>:</span>
                </td>
                <td class="sectionCenter">
                    <span id="contentLabel"></span>
                </td>
                <td class="sectionRight">
                    <img runat="server" src="images/noselected.png" class="selectImage" />
                </td>
            </tr>
        </table>
    </div>
</div>

and i want to set text to numberLabel and contentLabel

$(document).ready(function () {
        var counter = 1;

        var content = ["val1", "val2", "val3", "val4", "val5"];

        $('#AddSectionButton').click(function () {
            var section = $('#editCatalogListItemHideMe').html();
            $(section).find('#numberLabel').text(counter);
            $(section).find('#contentLabel').text(content[counter % content.length]);

            $('div#editCatalogLeftBottomContent').append(section);

            counter++;

    });

This script appends empty div, without my values. How can i make this?

Upvotes: 1

Views: 1089

Answers (4)

Jamiec
Jamiec

Reputation: 136094

id's must be unique on a page, you are effectively cloning an existing element, and re-using the same id's. Change numberLabel and contentLabel in classes, and use .numberLabel and '.contentLabel inside your find's.

Also you're discarding your reference to $(section) - so create once and re-use

var section = $($('#editCatalogListItemHideMe').html());

Live example: http://jsfiddle.net/MwvJA/

Upvotes: 1

SLaks
SLaks

Reputation: 887315

Each time you write $(section), you're creating a detached DOM tree, manipulating it, and then discarding it.

You need to reuse and then append it.

Upvotes: 2

Hussam
Hussam

Reputation: 510

the line:

var section = $('#editCatalogListItemHideMe').html();

might be the evil-thing :) try changing it to :

var section = $('#editCatalogListItemHideMe');

Upvotes: 1

Rob W
Rob W

Reputation: 348982

Use this:

var $section = $($('#editCatalogListItemHideMe').html());
$section.find('#numberLabel').text(counter);
$section.find('#contentLabel').text('text', content[counter % content.length]);
$('div#editCatalogLeftBottomContent').append($section);

In your current code, you're defining section as a string. Then, at the lines following the section declaration, you're wrapping the value in a JQuery object. This will modify the contents of the newly created object, but not the section variable.

I've adjusted your code, so that $section is a variable which refers to a newly created JQuery object. The lines after the declaration operate on the newly created object. At the end of the code, the HTML is appended.

Upvotes: 3

Related Questions