...

View Full Version : retrieve the element's order



Kor
02-12-2004, 10:31 AM
What propriety can return the index (the order) of an element?

Ex

<html>
<head>
<script>
function bla(obj){
alert(obj.what_property_to_show_the_index?)
}
</script>
</head>

<body>
<form>
<input name="q0" type="checkbox" onclick="bla(this)">
<input name="q0" type="checkbox" onclick="bla(this)">
<input name="q0" type="checkbox" onclick="bla(this)">
</form>
</body>
</html>

If click the first, I expect to see 0, the second 1 and so on....

glenngv
02-12-2004, 11:02 AM
You have to loop thru formObj.elements collection to find the match and then return the index

Kor
02-12-2004, 11:08 AM
You mean something like?:

function bla(a){
c = new Array()
for(i=0;i<3;i++){
c[i]=document.forms[0].elements[a.name][i].checked;
if(c[i] == true){alert(i)}
}
}

I knew that, but I was looking for smth simplier....

glenngv
02-12-2004, 11:32 AM
function bla(obj){
var f = obj.form;
for (var j=0;j<f.elements.length;j++){
if (f.elements[j].name==obj.name) return j;
}
return -1; //does not exist
}

Kor
02-12-2004, 12:19 PM
Yeap, thanks. Your code is a general approach and I see I can use it no matter the type of elements or events.

Garadon
02-12-2004, 12:30 PM
my odd suggestion :), note mine alerts what index the clicked check box has. in the check box group of its own name



function bla(obj){
var group=document.getElementsByName(obj.name);
for(I=0;I<group.length;I++)
{
if(group[I]==obj)
{
alert(I);
}
}
}

Kor
02-12-2004, 12:48 PM
Yes, thanks. You guess I need a group reference. But I needed to have a code even for NS4, so I had to search for a classical way, not a DOM method. So I did it this way

Here's the final code for I needed that index:



<html>
<head>
<script>
var nq = 3;//input the number of questions
var nc = 3;//input the number of checkboxes on a question
//no need to modify below
var x;
function bla(a){
c = new Array()
for(i=0;i<nc;i++){
c[i]=document.forms[0].elements[a.name][i].checked;
if(c[i] == true){x=i}
}
n = new Array()
for(j=0;j<nq*nc;j++){
n[j]= document.forms[0].elements[j].name;
for(i=0;i<nc;i++){
if(i==x){
document.forms[0].elements[n[j]][i].disabled = true;
}
}
}
}
</script>
</head>

<body>
<form >
Q1<br><br>
<input name="q0" type="checkbox" onclick="bla(this)">
<input name="q0" type="checkbox" onclick="bla(this)">
<input name="q0" type="checkbox" onclick="bla(this)"><br>
<br>
Q2<br><br>
<input name="q1" type="checkbox" onclick="bla(this)">
<input name="q1" type="checkbox" onclick="bla(this)">
<input name="q1" type="checkbox" onclick="bla(this)">
<br>
<br>
Q3<br><br>
<input name="q2" type="checkbox" onclick="bla(this)">
<input name="q2" type="checkbox" onclick="bla(this)">
<input name="q2" type="checkbox" onclick="bla(this)">
</form>
</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum