Search code examples
phpjqueryclone

How to change id or each field by using jQuery


i want the result must to be like,

<tr class="tr_cond"> 
<td>BLA</td>
<td>BLA</td>
<td>BLA</td>
<td>BLA</td>
<td><input type="button" class="tr_condition" value="+" name="add"></td>
</tr>
<tr class="tr_cond" id="tablCond1"> 
<td id="tablCond1>BLA</td>
<td id="colCond1>BLA</td>
<td id="operCond1>BLA</td>
<td id="valCond1>BLA</td>
<td><input type="button" class="tr_condition" value="+" name="add"></td>
</tr>
<tr class="tr_cond"> 
<td id="tablCond2>BLA</td>
<td id="colCond2>BLA</td>
<td id="operCond2>BLA</td>
<td id="valCond2>BLA</td>
<td><input type="button" class="tr_condition" value="+" name="add"></td>
</tr>
<tr class="tr_cond"> 
<td id="tablCond3>BLA</td>
<td id="colCond3>BLA</td>
<td id="operlCond3>BLA</td>
<td id="valCond3>BLA</td>
<td><input type="button" class="tr_condition" value="+" name="add"></td>
</tr>

And the jQuery is,

$(".tr_condition").live('click', CloneCondition);
var cloneCount = 1;
function CloneCondition(){
    $(this).closest('.tr_cond')
        .clone()
        .attr('id', 'tablCond'+ cloneCount++)
        .insertAfter(".tr_cond:last"); 
}

which is working to clone the row, but I want to change the id of those fields inside the row, but this only changes the id of the row.


Solution

  • To which field you want to add an ID ? to the input ?
    In the meanwhile:

    Use the .on() method for elements that are dynamically added to the document

    http://jsbin.com/uharaw/5/edit

    $("table").on('click', '.tr_condition', CloneCondition);
    
    var addIDs = ['tabl','col','oper','val'];
    var cloneCount = 0;
    
    function CloneCondition(){
    
        cloneCount++;
    
        $(this).closest('.tr_cond')
            .clone()
            .insertAfter(".tr_cond:last");
    
        // after clone is done let's go for the last (new) one
        $('.tr_cond:last td').not(':last').each(function(i){
           $(this).attr('id', addIDs[i] +'Cond'+ cloneCount);
        });
    
    }
    

    which after a couple of clicks results in:

    <tr class="tr_cond"> 
        <td>BLA</td>
        <td>BLA</td>
        <td>BLA</td>
        <td>BLA</td>
        <td><input name="add" value="+" class="tr_condition" type="button"></td>
    </tr>
    <tr class="tr_cond"> 
        <td id="tablCond1">BLA</td>
        <td id="colCond1">BLA</td>
        <td id="operCond1">BLA</td>
        <td id="valCond1">BLA</td>
        <td><input name="add" value="+" class="tr_condition" type="button"></td>
    </tr>
    <tr class="tr_cond"> 
        <td id="tablCond2">BLA</td>
        <td id="colCond2">BLA</td>
        <td id="operCond2">BLA</td>
        <td id="valCond2">BLA</td>
        <td><input name="add" value="+" class="tr_condition" type="button"></td>
    </tr>