Radio buttons values removes while Cloning in jquery

479 views Asked by At

I want to clone a table (Not a table Row) with textboxes and radio buttons in it.

More specifically, I want to clone whole table without textbox values but with radio button values.

Here, textbox and radio button values get removed while cloning. How can I obtain the desired behavior ?

Here, is my code :

<div>
<table id="tablePreviousHistory">
    <tbody>
        <tr>
            <td>
                <input id="pCountry" name="pCountry" value="" type="text">
            </td>
            <td>
                <input id="pvisatype" name="pvisatype" value="" type="text">
            </td>
            <td>
                <input id="pstartdate" name="pstartdate" value="" type="text">
            </td>
            <td>
                <input id="pStatus" name="pStatus" value="Yes" type="radio">
                Yes<br>
                <input id="pStatus" name="pStatus" value="No" type="radio">
                No
            </td>
        </tr>
    </tbody>
</table>
</div>

Javascript:

 <script>
$("#tablePreviousHistory").clone(true).attr('id', 'tablePreviousHistory' + k).find("input").val('').each(function () {
                if (this.type=='radio') {
                    this.checked = false;
                }
                $(this).attr({
                    'id': function (_, id) { return id + k },
                    'name': function (_, name) { return name + k }
                });
            }).end().insertAfter("#tablePreviousHistory" + (k != 1 ? (k - 1).toString() : ''));
</script>

3

There are 3 answers

2
dading84 On

The text inputs are cleared in this line of code with val('')

$("#tablePreviousHistory").clone(true).attr('id', 'tablePreviousHistory' + k).find("input").val('').each(function () {

If you replace that line with this one below, then they should no longer clear.

$("#tablePreviousHistory").clone(true).attr('id', 'tablePreviousHistory' + k).find("input").each(function () {
2
ScanQR On

It is because of while cloning it is unchecked by following,

 if (this.type=='radio') {
        this.checked = false;
 }
0
Aditya On

I think I found the issue with help of this answer

Here is my function to clone a table row, it should help in similar issue

/**
 * Add QC Row
 *
 * @param element $ele
 * @param integer $currentRowIndex
 * 
 * @return void
 */
function addRow(ele,currentRowIndex) {
    let row = $(ele).parents("tr");
    let clone = $(row).clone(true); // copy children too       
    $(clone).find(".parameter_test_text_value").val('');
    $(clone).find(".parameter_test_min_value").val('');
    $(clone).find(".parameter_test_max_value").val('');
    $(clone).find(".remark").val('');
    $(clone).find(".add-param").addClass('displayNone');
    $(clone).find(".remove-param").removeClass('displayNone');
    //First change the name index for the cloned row so that it does not disturb other
    //values
    $(clone).find('input[type=radio]').each(function () {
        let str = this.name;
        let str_split = str.split('[');
        str_split[1] = str_split[1].replace(']', '');
        str_split[2] = str_split[2].replace(']', '');
        str_split[3] = !empty(str_split[3]) ? str_split[3].replace(']', '') : '';
        let mainid ='';
        if(!isNaN(str_split[2])){
            mainid = str_split[0]+"["+str_split[1]+"][20000000]["+str_split[3]+"]";                
        } else {
            // Remove numbers by first regexp
            mainid = str_split[0]+"[20000000]["+str_split[2]+"]";
        }
        this.name = mainid;
        $(this).val('').trigger('change');
    });

    //Create new index first before cloning so that the values are retained
    let parameterAllRows = $(".container-itemprameter tr");
    $.each(parameterAllRows, function(index) {
        index+=200000;
        $(this).find('input[name^="QiParameterTestResult"]').each(function () {
            let str = this.name;
            let str_split = str.split('[');
            str_split[1] = str_split[1].replace(']', '');
            str_split[2] = str_split[2].replace(']', '');
            str_split[3] = !empty(str_split[3]) ? str_split[3].replace(']', '') : '';
            let mainname='';
            if(!isNaN(str_split[2])){
                mainname = str_split[0]+"["+str_split[1]+"]["+index+"]["+str_split[3]+"]";
            } else {
                // Remove numbers by first regexp
                mainname = str_split[0]+"["+index+"]["+str_split[2]+"]";
            }
            $(this).prop('name',mainname);
        });
    });

    //Now insert the row
    $(row).after(clone);

    //Now rearrange the indexes properly
    parameterAllRows = $(".container-itemprameter tr");
    $.each(parameterAllRows, function(index) {
        $(this).find('input[id^="QiParameterTestResult-"]').each(function () {
            let str = this.id;
            let str_split = str.split('-');
            let mainid='';
            if(!isNaN(str_split[2])){
                mainid = str_split[0]+"-"+str_split[1]+"-"+index+"-"+str_split[3];
            } else {
                // Remove numbers by first regexp
                mainid = str_split[0]+"-"+index+"-"+str_split[2];
            }
            $(this).prop('id',mainid);
        });
    
        $(this).find('input[name^="QiParameterTestResult"]').each(function () {
            let str = this.name;
            let str_split = str.split('[');
            str_split[1] = str_split[1].replace(']', '');
            str_split[2] = str_split[2].replace(']', '');
            str_split[3] = !empty(str_split[3]) ? str_split[3].replace(']', '') : '';
            let mainname='';
            if(!isNaN(str_split[2])){
                mainname = str_split[0]+"["+str_split[1]+"]["+index+"]["+str_split[3]+"]";
            } else {
                // Remove numbers by first regexp
                mainname = str_split[0]+"["+index+"]["+str_split[2]+"]";
            }
            $(this).prop('name',mainname);
        });
    });
}

I have copied the entire code as it is so that it helps to understand in details what exactly needs to be done.