Roberto
Roberto

Reputation: 809

use find and replace with jquery

my html

<div id="sample-reminder">
    <div id="reminder_0000">
        <input type="text" name="val_0000" value="1">
    </div>
</div>

my code

rigaHtml = $('#sample-reminder').clone(); // i have to work on a clone of dom
rigaHtml.find('input[name^=val_]').val(99);
rigaHtml.html().replace(/0000/g, 987654321); 

last command not replace my placeholder '0000'. if i move replace() before find(), i cant' use find :-(

Upvotes: 2

Views: 136

Answers (4)

Rory McCrossan
Rory McCrossan

Reputation: 337713

Assuming you are looking to change the id property of #reminder_0000 and the name property of val_0000, try this:

$rigaHtml = $('#sample-reminder').clone();
var $input = $("input", $rigaHtml);
var $div = $input("div", $rigaHtml);

$input.val(99).attr("name", $input.attr("name").replace(/0000/g, 987654321));
$div.attr("id", $div.attr("id").replace(/0000/g, 987654321));

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173662

You don't need to use .clone() in this case:

var rigaHtml = $('#sample-reminder').html();
$(rigaHtml.replace(/0000/g, 987654321))
  .find('input[name^=val_]')
  .val(99)
  .appendTo('#container')

Where '#container' is the node you wish to add the modified HTML to.

Upvotes: 2

Jon
Jon

Reputation: 437854

You are not doing anything with the returned value of replace. That should be written as:

rigaHtml.html(rigaHtml.html().replace(/0000/g, 987654321)); 

Even then, rigaHtml is not in the DOM because it's a clone of the original elements. So you still wouldn't see a visible change unless you put it back inside the DOM.

Upvotes: 0

xdazz
xdazz

Reputation: 160963

You need to set the result back.

var html = rigaHtml.html().replace(/0000/g, 987654321);
rigaHtml.html(html);

Upvotes: 0

Related Questions