PDA

View Full Version : Re-numbering a list


Iauwak
12-07-2007, 10:10 PM
Basically I have a page with ordered elements. When I remove an element I want the page to re-order the numbers on it.

For example.. If I have:
1.
2.
3.
4.
5.

Say I remove number 3, I should have:
1.
2.
3.
4.

I tried to make a function that will re-order these, but nothing I seem to make will work.

for (i = 1; i <= xarr.count; i++) {
document.getElementById('test'+i+'').innerText = i;
}

The HTML codes are in span blocks for example:

<span id="test1">1.</span><span id="test2">2.</span><span id="test3">3.</span>

I keep getting an error that test +i+ has no properties.

GO ILLINI
12-07-2007, 11:27 PM
HTML has a tag for exactly this.

<ol>
<li>List item one
<li>List item 2
<li>List item 3
<li>List item 4
<li>List item 5
</ol>
remove one and see what happens!

-Adam

rnd me
12-08-2007, 01:57 AM
for (i = 1; i <= xarr.count; i++) {
document.getElementById('test'+i+'').innerText = i;
}


i <= xarr.count;
should be
i < xarr.count;

-----

when = count, it is 1 over the last index...
and you may want to start a 0 instead of 1.

know how javascript counts to 10:
0,1,2,3,4,5,6,7,8,9


--- also , this code wont work in firefox (or other browsers) as is
fix it like so:



for (i = 0; i < xarr.count; i++) {
document.getElementById('test' + (i+1) ).innerHTML = (i+1) + ". ";
}

Iauwak
12-08-2007, 02:12 AM
The OL solution seems to work. I cannot get the JS to work though.

Iauwak
12-08-2007, 02:21 AM
Firefox complains: document.getElementById("test" + (i + 1)) has no properties

Trinithis
12-08-2007, 05:56 AM
How about:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Test</title>
</head>

<body>
<div>

<span id="test1">1. Lorem</span>
<span id="test2">2. Ipsum</span>
<span id="test3">3. Dolor</span>
<span id="test4">4. Sit</span>
<span id="test5">5. Amet</span>

<script type="text/javascript">

if(!Array.prototype.filter) {
Array.prototype.filter = function(f /*, context*/) {
for(var i = 0, n = this.length, r = [], t = arguments[1], v; i < n; ++i) {
v = this[i];
if(f.call(t, v, i, this))
r.push(v);
}
return r;
};
}

document.getElementsByRegex = function(r) {
return Array.prototype.filter.call(
this.getElementsByTagName(typeof r.tagName == "string"
? r.tagName
: "*"
), document.getElementsByRegex.filterer, r);
};

document.getElementsByRegex.filterer = function(el) {
for(var x in this)
if(this[x] instanceof RegExp)
if(!this[x].test(el[x]))
return false;
else;
else if(this[x] !== el[x] && x !== "tagName")
return false;
return true;
};

/////////////////////////////////////////////////////////////

var spans = document.getElementsByRegex({tagName: "span", id: /^test\d+$/});

spans[2].parentNode.removeChild(spans.splice(2, 1)[0]);

for(var i = spans.length - 1, t; i >= 0; --i) {
spans[i].id = "test" + (i + 1);
t = spans[i].firstChild;
t.nodeValue = t.nodeValue.replace(/^\d+/, i + 1);
}

</script>
</div>
</body>
</html>