Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in cloned jquery object

in the following script I clone a new row form tfoot and append it to table tbody

<script>
$('#checklist-builder .add-row').click(function(){
    var new_row = $('#checklist-builder>tfoot>tr').clone();
    $('#checklist-builder>tbody').append(new_row);
});
</script>

cloned row is:

<tr>
  <td>${j}</td>
  <td>
    <input size="2" type="hidden" value="" name="WhoChecklistField[1][${j}][id]" id="WhoChecklistField_1_${j}_id">      <input size="2" maxlength="2" type="text" value="" name="WhoChecklistField[1][${j}][weight]" id="WhoChecklistField_1_${j}_weight">    </td>
  <td>
    <input type="text" value="" name="WhoChecklistField[1][${j}][name]" id="WhoChecklistField_1_${j}_name">    </td>
  <td>
    <select size="1" name="WhoChecklistField[1][${j}][type]" id="WhoChecklistField_1_${j}_type">
      <option value="text">Text field</option>
      <option value="select">Select field</option>
      <option value="radio">Radio field</option>
      <option value="checkbox">Checkbox field</option>
    </select>
  </td>
</tr>

now I want replace ${j} with table size + 1, how can I replace ${j} in jquery cloned string?

like image 295
Mohammad Ali Akbari Avatar asked Jul 01 '12 06:07

Mohammad Ali Akbari


3 Answers

new_row.html(function(i, oldHTML) {
    return oldHTML.replace(/\${j}/g, 'table_size');
});

DEMO

like image 130
thecodeparadox Avatar answered Oct 19 '22 22:10

thecodeparadox


From my own problem i came up with below code that works also and maybe will help someone (full example)

$j('grab_object')
.clone()
.html(function(i, oldHTML) {
    return oldHTML.replace(/regular_expression/, change_found_expression_to_this);
}))
.appendTo('paste_object_here');

And You should recieve cloned and pasted object with changed part of its code. In my case I was changing [nr] with a number and my expression was like below

(...).replace(/\[nr\]/g, $j('#some_id').val().(...)

Also due to documentation remember that with clone() jQuery also copies attributes including id and this can cause some issues in further manipulation in DOM.

like image 42
ThePueblo Avatar answered Oct 19 '22 23:10

ThePueblo


Before you append just do:

new_row.html(function(i, oldHtml){ return oldHtml.replace(/${j}/g, tSize) });
like image 42
mVChr Avatar answered Oct 19 '22 22:10

mVChr