Reputation: 111839
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)
Questions:
for
for label also be updatedUpvotes: 2
Views: 840
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
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