Jess McKenzie
Jess McKenzie

Reputation: 8385

input array within jquery

Within my code below how can I make it read name="item[]" and name="amount[] from my HTML?

I have seen a few conflicting things on here how to do it is there a simple way?

HTML:

<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item[]" /><span class="bookingName">Amount<span class="required">*</span></span><input type="text" name="amount[]"></span>

jQuery:

$(document).ready(function () {

    $('<div/>', {
        'class': 'menuDetails',
        html: getMenuHTMLDetails()
    }).appendTo('#addMoreItemsButton');
    $('#addItem').click(function () {
        $('<div/>', {
            'class': 'extraMenuItem',
            html: getMenuHTMLDetails()
        }).hide().appendTo('.appendMoreItems').slideDown('slow');
    });
})

function getMenuHTMLDetails() {
    var len = $('.extraMenuItem').length;
    var $clone = $('.menuDetails').clone();

    $clone.find('[name=item]')[0].name = "item" + len;
    $clone.find('[name=amount]')[0].name = "item" + len;
    return $clone.html();
}

Upvotes: 1

Views: 69

Answers (2)

Ram
Ram

Reputation: 144729

You can either put the attribute's value in quotes:

$clone.find('[name="item[]"]').prop("name", "item" + len);

or escape the []:

$clone.find('[name=item\\[\\]]').prop("name", "item" + len);

Upvotes: 1

Sergey
Sergey

Reputation: 133

You must use quotes '"' $('[name="item[]"]')

Upvotes: 1

Related Questions