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.
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;
    });
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With