Purusartha
Purusartha

Reputation: 1010

Jquery replace part of id

I am trying to dynamically add a new row in my table by cloning the last row and modifying its id, so that my MVC ModelBinder picks that up when I submit the form. Below is the html generated for the table:

<tr id="trImg_-1">
<td>
    <div class="form-group">
        <input id="MediaList_0__MediaCaption" class="form-control" type="text" value="Blah" name="MediaList[0].MediaCaption" data-val-required="The Image Caption field is required." data-val="true">
        <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="MediaList[0].MediaCaption"></span>
    </div>
</td>
<td>
    <input id="MediaList_0__MediaCaptionDescription" class="form-control" type="text" value="Caption Desc" name="MediaList[0].MediaCaptionDescription" data-val-required="The Image Caption Description field is required." data-val="true">
</td>
<td>
    <input id="MediaList_0__SortOrder" class="form-control" type="text" value="0" name="MediaList[0].SortOrder" data-val-required="The Sort Order field is required." data-val-number="The field Sort Order must be a number." data-val="true">
    0
</td>
<td>
    <img class="img-thumbnail" alt="Product Image" src="CurrentImage">
</td>
    <td>
    <button id="btnRemoveImage" class="btn btn-danger btn-sm" type="button">
    </td>
</tr>

I have implemented jquery to clone the row and create a new row, however I am struggling to change the index from MediaList_0__MediaCaption to MediaList_1__MediaCaption for all the inputs within this. Any ideas?

Below is the jquery I am using

var $tableBody = $('#tblImage').find("tbody");
        $trLast = $tableBody.find("tr:last");           // find last row
        $trNew = $trLast.clone();                       // clone to new row

        var tr_Id = $($trNew).attr('id');       // get row id *Mashed*
        var arr_RowStr = tr_Id.split('_');         // extract the indexarr_Row[1]
        var tr_RowIdOld = parseInt(arr_RowStr[1], 10);  // 10 is for decimal [Base 10]
        var tr_RowIdNew = tr_RowIdOld + 1;              // get new id

        var tr_FullNew = arr_RowStr[0] + '_' + tr_RowIdNew;     // get new id

        $trNew.attr('id', tr_FullNew);

        $trNew.find('input:text').val('');

        $trLast.after($trNew);

Upvotes: 2

Views: 1202

Answers (3)

HandsomeG
HandsomeG

Reputation: 113

  1. Find the last row
  2. clone the last row and store it in a variable
  3. find all elements that you want attributes to be changed
  4. Use a regex to remove all non-numeric from the attribute and store in a variable
  5. add 1 to the variable and replace the current attr using attr("id").replace(currrentID, newID)

See the following code below

Hope that helps.

HTML

    <table id="tbl">

    <tr id="trImg_-1">
    <td>
        <div class="form-group">
            <input id="MediaList_0__MediaCaption" class="form-control" type="text" value="Blah" name="MediaList[0].MediaCaption" data-val-required="The Image Caption field is required." data-val="true">
            <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="MediaList[0].MediaCaption"></span>
        </div>
    </td>
    <td>
        <input id="MediaList_0__MediaCaptionDescription" class="form-control" type="text" value="Caption Desc" name="MediaList[0].MediaCaptionDescription" data-val-required="The Image Caption Description field is required." data-val="true">
    </td>
    <td>
        <input id="MediaList_0__SortOrder" class="form-control" type="text" value="0" name="MediaList[0].SortOrder" data-val-required="The Sort Order field is required." data-val-number="The field Sort Order must be a number." data-val="true">
        0
    </td>
    <td>
        <img class="img-thumbnail" alt="Product Image" src="CurrentImage">
    </td>
     <td>
        <button id="btnRemoveImage" class="btn btn-danger btn-sm" type="button">
    </td>
</tr>
</table>

JS

   $(function() {

    $lastRow = $("#tbl #trImg_-1");
    $lastRowCopy = $lastRow.clone();

    $lastRowCopy.find("input, span").each(function(index, elem) {
        if ($(elem).attr('id')) {
             var id = $(elem).attr('id').replace(/[^\d]/g, '');
            var newId = $(elem).attr('id').replace(id, parseInt(id,10)+1);
            $(elem).attr('id', newId);   
        }

        if ($(elem).attr('name')) {
            var curName = $(elem).attr('name').replace(/[^\d]/g, '');
            var newName = $(elem).attr('name').replace(curName, parseInt(curName,10)+1);
            $(elem).attr('name', newName);
        }

        if ($(elem).attr('data-valmsg-for')) {
            var curDatavalFor = $(elem).attr('data-valmsg-for').replace(/[^\d]/g, '');
            var newDataValFor = $(elem).attr('data-valmsg-for').replace(curDatavalFor, parseInt(curDatavalFor,10)+1);
            $(elem).attr('data-valmsg-for', newDataValFor);
        }

    });  
    console.log($lastRowCopy);
    $lastRow.after($lastRowCopy);  
});

fiddle: http://jsfiddle.net/cGL5F/

Upvotes: 4

Ram
Ram

Reputation: 144669

You can use the String.prototype.replace method:

$collection.attr('id', function(_, id) {
    return id.replace(/\d+/, function(n) { return ++n; });
});

http://jsfiddle.net/f3nUB/

Upvotes: 1

Gao Wei
Gao Wei

Reputation: 79

I think you can try to use .removeAttr() method to remove the original id of the $trNew first, then use the attr() method to set the new id again.

Upvotes: 0

Related Questions