Skip to content

Instantly share code, notes, and snippets.

@pure
Created May 5, 2011 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pure/957827 to your computer and use it in GitHub Desktop.
Save pure/957827 to your computer and use it in GitHub Desktop.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>addRow</title>
</head>
<body>
<!-- avoid id's -->
<form>
<table border="0" id="shopinglist">
<caption valign="top" style="width:90%;height:35px; color:green ;"/> your order
<thead>
<tr>
<th></th>
<th>product</th>
<th>quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select data-name="product" width="10" >
<option value="default" selected>בחר מוצר מהרשימה</option>
<option value="product1">product1</option>
<option value="product2">product2</option>
</select>
</td>
<td>
<select data-name="quantity">
<option value="zero" selected="selected">0</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
<option value="six">6</option>
<option value="seven">7</option>
<option value="eight">8</option>
<option value="nine">9</option>
<option value="ten">10</option>
</select>
</td>
<td>
<input type="button" value="add" onclick="changeRow(this, 'add')" />
</td>
<td>
<input type="button" value="delete"onclick="changeRow(this, 'del')" />
</td>
</tr>
</tbody>
</table>
</form>
<script>
//utility function to find parents
function getParent(elm, tagName){
while(elm){
if(elm.tagName === tagName){
return elm;
}
elm = elm.parentNode;
}
return false;
}
function updateNames(tbody){
var trs = tbody.getElementsByTagName('TR'),
tr,
i = trs.length,
selects,
j,
newSelect,
name;
while(i--){
tr = trs[i];
selects = tr.getElementsByTagName('SELECT'); //find all selects in the new line
j = selects.length;//count them
while(j--){//for each
name = selects[j].getAttribute('data-name');
if((/MSIE (6|7|8)/).test(navigator.userAgent)){//special care for IE
newSelect = document.createElement('<SELECT NAME="'+name + '_' + i+'"></SELECT>');
newSelect.innerHTML = selects[j].innerHTML;
newSelect.setAttribute('data-name', name);
selects[j].parentNode.innerHTML = newSelect;
}else{
selects[j].name = name + '_' + i;//change the name
}
}
}
}
function changeRow(button, action){
var tr = getParent(button, 'TR'), //find the parent TR
newTr = tr.cloneNode(true), //make a copy of it
tbody = tr.parentNode;//get the parent
if(action === 'add'){
tbody.insertBefore(newTr, tr.nextSibling); //insert the new line in the table
}else{
tbody.removeChild(tr);
}
updateNames(tbody);//update names
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment