Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

jQuery - clone form elements and change labels for

I have a problem - I want to clone a part of HTML form but I have no idea how can I change label for attribute.

I'm using code like this:

<script>

    $('#add-service').click(function () {
        $('.services div.service:last').clone(true)
        .find(':input').each(function () {
            this.name = this.name.replace(/\[(\d+)\]/, function (str, p1) {
                return '[' + (parseInt(p1, 10) + 1) + ']';
            })

            this.id = this.name

        }).end().find('label').each(function () {
            $(this).css('background-color','red');
            $(this).attr('for', function (index, old) {
                old.replace(/\[(\d+)\]/, function (str, p1) {
                    return '[' + (parseInt(p1, 10) + 1) + ']';
                });
            })
        }).end().insertAfter('.services div.service:last');
    });

</script>

but for attribute for label is not updated (but background-color is)

Working fiddle

Questions:

  1. How to update above code to make for for label also be updated
  2. Is it possible to rewrite this code to make it shorter

Upvotes: 2

Views: 840

Answers (2)

Rafael Quintanilha
Rafael Quintanilha

Reputation: 1432

You need to return the new value after running replace.

$(this).attr('for', function (index, old) {
  return old.replace(/\[(\d+)\]/, function (str, p1) {
    return '[' + (parseInt(p1, 10) + 1) + ']';
  });
})

Upvotes: 2

Adjit
Adjit

Reputation: 10305

You have it right, but you are missing a return statement.

$(this).attr('for', function (index, old) {
    return old.replace(/\[(\d+)\]/, function (str, p1) {
        return '[' + (parseInt(p1, 10) + 1) + ']';
    });
})

Remember, you have 2 nested functions and each return only applies to the function you are currently inside.

Upvotes: 3

Related Questions