0

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.

2 Answers 2

3

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');
Sign up to request clarification or add additional context in comments.

Comments

2

newitem is the li and not the attribute. Try someting like this:

newitem.html(newitem.html().replace("ROWID",i));

3 Comments

you also can only edit the attributes via attr() function :) its nearly the same way!
thanks for your reply, unfortunately this hasn't worked for me. @nachito 's solution has though. Is it possible to flatten the jQuery object so that it's just html/text rather than a series of objects? Is that what you're trying to do with .html()?
if you're using .html() you get everything in your container as html or if you use .text() as text. then you can use every string manipulation you want. then you can insert it again. Just look at api.jquery.com/html and api.jquery.com/text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.