I have a table with 4 rows and then 2 buttons where I can clone the row or delete an added row. In 3 of the 4 rows, I am using a jquery autocomplete widget with a combobox.
<tbody id="table_body">
<tr id="tableRow">
<td id="theSupRow"><div class="ui-widget">
<select id="supplement" name="supplement">
<option></option>
{% for c in supplements %}
<option value={{c.supplement_description}}>{{c.supplement_description}}</option>
{% endfor %}
</select>
</div></td>
<td><div class="ui-widget">
<select id="brand" name="brand[]">
<option></option>
{% for c in brands %}
<option value={{c.brand_description}}>{{c.brand_description}}</option>
{% endfor %}
</select>
</div></div></td>
<td><input type = "text"
onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))"
name="dose[]"
id = "dose"
placeholder="1000"
class = "form-control"></td>
<td><div class="ui-widget">
<select id="measurement" name="measurement[]">
<option></option>
{% for c in measurements %}
<option value={{c.measurement_description}}>{{c.measurement_description}}</option>
{% endfor %}
</select>
</div></div></td>
<td>
<div class="action_container">
<button class="btn btn-danger" onclick="remove_tr(this)">
<i class="fa fa-close"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
If you click the add button, a JS function is called to clone the node and append a copy of the node onto the table, making a new row.
function create_tr(table_id) {
let table_body = document.getElementById(table_id),
first_tr = table_body.firstElementChild
tr_clone = first_tr.cloneNode(true);
var i = table_body.rows.length;
table_body.append(tr_clone);
}
I originally wanted to just have all the comboboxes have the same name, for example supplement[], that way I could grab the data as an array when I submit the form. The comboboxes will not initialize if their id's contain [], so that won't work. What I thought I was doing with the code above was changing the id of the element, adding the row number. I can initialize the combobox, but then I get 2 comboboxes in the same row, one is a dead control and the other is an autocomplete box like I wanted.a picture of that double combobox in the added row
//this is where i was playing around trying to change the id to initialize the combobox
tr_clone.getElementsByTagName('select')[0].id = "supplement"+i
alert(tr_clone.getElementsByTagName('select')[0].id)
$( "#supplement1" ).combobox();
Maybe I am going about this all wrong? I really want a way where I can easily add table rows and just have that autocomplete widget work seemlessly on each row. not sure if there is another way to do it besides changing the ids of the controls via Javascript.
I've been at this for too long. Hopefully someone has the solution.