Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending multiple items using jQuery

I start with this markup:

<div>
  <span>
    <label for="Item[0]">Item #1</label>
    <input type="text" value="" name="Item" id="Item[0]"/>
  </span>
</div>

On each button click I want to add another section exactly as the one above but with an incremented index.

<div>
  <span>
    <label for="Item[0]">Item #1</label>
    <input type="text" value="" name="Item" id="Item[0]"/>
  </span>
</div>
<div>
  <span>
    <label for="Item[1]">Item #2</label>
    <input type="text" value="" name="Item" id="Item[1]"/>
  </span>
</div>

I'm trying to use this javascript:

 $(document).ready(function(){

    var count = <%= Items.Count - 1 %>;

    $('#AddItem').click(function(e) {
        e.preventDefault();
        count++;

        var tb = $('#Item[0]').clone().attr('id', 'Item[' + count + ']');

        var label = document.createElement('label')
        label.setAttribute('For', 'Item[' + count + ']')

        $('#ItemFields').append(label);
        $('#ItemFields').append(tb);
    });
});

So a few issues:

Appending the label works, but my cloned textbox does not.

The label has no text. I can't seem to find the property for that. Can anyone tell me what it is?

I can't figure out how to wrap the label and textbox together in a div and span. If I try

$('#ItemFields').append('<div><span>' + label + tb + '</span></div>');

it outputs [object HTMLLabelElement] instead of the actual label. If I try to split them up into multiple append statements, it self terminates the div and span. I'm new to jQuery/Javascript, so I'm not quite sure what I'm doing wrong.

like image 547
Brandon Avatar asked Oct 23 '09 20:10

Brandon


1 Answers

I think I'd find a way to extract the next number from the existing ones in the mark up rather than relying on keeping variable in sync. Also, I think you simply need to nest your appends properly to get the containment that you want.

$(document).ready(function(){

    $('#AddItem').click(function(e) {
        var count = $('[name=Item]:last').attr('id').replace(/Item\[/,'').replace(/\]/,'');
        count = Number(count) + 1;

        var newItemID = 'Item[' + count + ']';

        var tb = $('#Item[0]').clone();
        tb.attr('id', newItemID );

        var label = $('<label for="' + newItemID + '">Item #' + count + '</label>');

        var container = $('<div></div>');

        $('<span></span>').append(label)
                          .append(tb)
                          .appendTo(container);

        $('#ItemFields').append(container);
        return false;
    });
});
like image 80
tvanfosson Avatar answered Sep 18 '22 03:09

tvanfosson