candies candies - 6 months ago 12
HTML Question

How do I change the select id's name after adding table rows?

In the table I have two selects, both are getting the values from database.
When pressing add button to add a new row, I want to change select id's name to be

facility2, currency2
facility3, currency3

and so on. But I do not know how to change them.

This is the table I have created:

<table id="tableInformation">
<tr>
<td><label>No</label></td>
<td><label>Facility</label></td>
<td><label>Currency</label></td>
<td></td>
</tr>
<tbody>
<tr>
<td><label>1</label></td>
<td><div id="facility">
<select id="facility1" name="facility">
<option value=""></option>
<option value="AL">AL</option>
<option value="BL">BL</option>
<option value="CL">CL</option>
</select>
</td>
<td><div id="currency">
<select id="currency1" name="currency">
<option value=""></option>
<option value="idr">IDR</option>
<option value="usd">USD</option>
<option value="aud">AUD</option>
<option value="jpy">JPY</option>
</select>
</td>
<td><input type="button" id="btnAddRows" value=" + "
onclick=\'addRows()\' />
</tr>
</tbody>
</table>


And this is the javascript:

function addRows() {
var table = document.getElementById('tableInformation');
var rowCount = table.rows.length;
var iteration = rowCount -1;
var numbers = iteration +1;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;

// Cell for number
var cell = row.insertCell(0);
var label = document.createElement('label');
label.textContent = numbers;
cell.appendChild(label);

for(var i=1; i<colCount; i++) {

var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(table.rows[1].cells[i].innerHTML);
//alert(newcell.childNodes);

}

}


Thanks in advance.

Answer

Lots of ways to do this. Here's a short addition to what you currently have.

Add:

.replace(/id="(.+)1"/, 'id="$1' + rowCount + '"')

...to:

table.rows[1].cells[i].innerHTML

EXPLANATION: You're copying the HTML from first row into the new row. The replace function replaces the number 1 in the id attribute value to whatever the new row number is, using the variable rowCount.

The replace function pattern (first argument) looks for the regular expression pattern: /id="(.+)1"/,

  • A string starting with id=",
  • Then capture one or more characters of any kind (.+),
  • And a number 1 followed by a quote 1".

The $1 in the replacement (second argument) provides the value of the text captured in (.+).

Here's the resulting for block:

for(var i=1; i<colCount; i++) {
  var newcell = row.insertCell(i);
  newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/id="(.+)1"/, 'id="$1' + rowCount + '"');
}

JSFiddle example.

Comments