Piotr wrote:
how can I read (in alert for example) array index number of checked
checkbox?
I have:
<input type="checkbox" id="id_number[]" name="check[]" value="1"
onclick="show()"/>
<input type="checkbox" id="id_number[]" name="check[]" value="2"
onclick="show()"/>
<input type="checkbox" id="id_number[]" name="check[]" value="3"
onclick="show()"/>
function show()
{
alert(here: display clicked id or name number of index? (for value "3" i
should be 2))
}
sorry for my english :)
Piotr,
You should not have duplicate id's, they should be unique. Most browsers will tolerate it, but it is contrary to the HTML spec. Any attempt to access the elements by id e.g. document.getElementById('id_number[]'), will likely return the first element only and may well cause an error.
Each of the elements in a form has a unique index, but the index is sequential across all the elements - there is no separate index for checkboxes and buttons. So if you put another element in the form, the index of all subsequent elements will be incremented by 1.
You can create an array of checkboxes by giving them all the same name and using a method like that below, but I'm not sure that it's a good idea. Presumably users willl be selecting a checkbox next to some value - why not just report the value?
Probably the best way to do what you ask is to give them a name equal to the index you'd like them to have, such as checkbox_1, checkbox_2, etc. This way you define exactly what the index is rather than using the order in some arbitrary array.
Using square brackets may cause you grief too but it's not fatal.
Below is some code that creates an array of input elements and reports the ones that are checked using both 'nodeType' and 'name' to create arrays. It also does a getElementById to show what happens with non-unique id's.
For the index method, the button is included in the array. If you put it at the top, the checkbox indices are all incremented by 1. For the name method, it isn't.
Cheers, Rob.
<form name="aForm">
<input type="checkbox" id="id_number[]"
name="check[]" value="1"
onclick="show()"/>
<input type="checkbox" id="id_number[]"
name="check[]" value="2"
onclick="show()"/>
<input type="checkbox" id="id_number[]"
name="check[]" value="3"
onclick="show()"/>
<input type="button" value="Input index"
onclick="
var a=this.form.elements;
var msg = document.getElementById('id_number[]');
for (var i=0;i<a.length;++i) {
msg += '\nnodeName ' + i + ': ' + a[i].nodeName
+ ' nodeType ' + a[i].nodeType
+ ' is';
if (!a[i].checked) msg += ' not ';
msg += ' checked.';
}
alert(msg);
">
<input type="button" value="Name index" onclick="
var c = 0;
var a=this.form.elements;
var msg = document.getElementById('id_number[]');
for (var i=0;i<a.length;++i) {
if (a[i].name == 'check[]'){
++c;
msg += '\nCheckbox ' + c
+ ' is';
if (!a[i].checked) msg += ' not ';
msg += ' checked.';
}
}
alert(msg);
">
</form>