Reputation: 984
I've been searching for ages and can't seem to find an answer to what I would think is quite a simple question. I've used .clone()
to make a copy of a li
containing several form fields and then i'm inserting it at the beginning of the form. This works fine.
What I am trying to do is find and replace all instances of ROWID
with variable i
<ul class="form">
<li class="hide">
<ol class="form">
<li><label for="cat_id_ROWID">Category:</label>
<select id="cat_id_ROWID" name="cat_id[]">
<option>...options...</option>
</select>
</li>
<li>
<label for="value_ROWID">Value:</label>
<input id="value_ROWID" name="value[]">
</li>
<li>
<label for="description_ROWID">Description:</label>
<textarea id="description_ROWID" name="description[]"></textarea>
</li>
</ol>
</li>
</ul>
Any my jquery is:
var newitem = $('li.hide').eq(0).clone();
newitem.removeClass('hide').addClass('row');
$(newitem).insertBefore('ul.form li:first');
I'm trying to do something like $(newitem).replace('ROWID',i);
but it doesn't work. Any help would be appreciated! Thanks.
Upvotes: 0
Views: 2507
Reputation: 7035
Your newitem
variable is a jQuery object, not a string, so a simple .replace
won't work. You'll have to select the elements you want within newitem
and change the attributes (which are strings) individually.
var $newitem = $('li.hide').eq(0).clone();
$('[for$="ROWID"]', $newitem).each(function () {
$(this).attr('for', $(this).attr('for').replace('ROWID', i));
});
$('[id$="ROWID"]', $newitem).each(function () {
$(this).attr('id', $(this).attr('id').replace('ROWID', i));
});
$newitem.removeClass('hide').addClass('row');
$newitem.insertBefore('ul.form li:first');
Upvotes: 3
Reputation: 3909
newitem is the li
and not the attribute.
Try someting like this:
newitem.html(newitem.html().replace("ROWID",i));
Upvotes: 2