Dynamically changing property name on button click in JavaScript

I am adding rows to a table when the add button is clicked.

Each line contains text fields for name, class, year.

For the first line, the property name will be ...... name_1, class_1, year_1.
For the second line, the property name will be ...... name_2, class_2, year_2.

If I remove the 1st row (name_1, class_1, year_1) the property name of the second row should become

name_2,class_2,year_2 <==> name_1,class_1,year_1

      

How can i do this?

0


a source to share


2 answers


I wouldn't do this on the client side. In your server-side code, just check if the key exists in the POST array.

If you still want to rename the elements:



var f = document.myForm;
var removeThisOne = 3;
var current = removeThisOne + 1;

while (f['name_' + current]) {
    f['name_' + current].name = 'name_' + (current - 1);
    f['class_' + current].name = 'class_' + (current - 1);
    // etc
    ++current;
}

      

0


a source


you could do something like this (untested, should pretty much work ...)

The 'delegate' internal method is needed to keep the scope in a string.

Setting:



var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
document.appendChild(table); // or wherever you want it.

      

add line:

function clickHandler( row )
{
    function delegate()
    {
        tbody.removeChild(row);
    }
    return delegate;
}
for (var i in someObj)
{
    var row = document.createElement('tr')
    var td1 = document.createElement('td');
    var td2 = etc...

    td1.innerHTML = someObj[i].field1;
    row.appendChild(td);
    td2 = etc...

    var del = document.createElement("input");
    input.type="button";
    input.value = "delete";
    input.onclick = clickHandler(row);
    tdX.appendChild(del);

    tbody.appendChild(row);
}

      

0


a source







All Articles