I have a web page with a table and a “remove row” link in each row of the table.
Problem is, when I click to delete a row, the browser does a page refresh. How do I prevent his from happening?
Here’s a complete functioning HTML page. Try it, scroll down to the rows, click a link causes the scrollbar to jump back up to the top:
NOTE: I’m using Firefox 11.
<SCRIPT language="javascript">
function deleteRow(rowID) {
try {
var table = document.getElementById("mytable");
var iRowIndex = 0;
while (iRowIndex < table.rows.length) {
var row = table.rows[iRowIndex];
if (row.id == rowID) {
table.deleteRow(iRowIndex);
} else {
iRowIndex++;
}
}
} catch (e) {
alert(e);
}
}
</SCRIPT>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<table id="mytable">
<tr id="foo" >
<td>FOO</td>
<td>
<a href="#" onclick="deleteRow('foo')">remove</a>
</td>
</tr>
<tr id="bar" >
<td>BAR</td>
<td>
<a onclick="deleteRow('bar')">remove</a>
</td>
</tr>
</table>
Any ideas?
The reason your page is refreshing is because of the
href="#"in your anchor tag. Removing that should make your example work.Removing the
href="#"snippet will also removing the selector cursor on hover of the anchor element. If you wish to maintain that styling, it’s easy to fix with a little css.