Page 1 of 1

help use the array checkbox in javascript

Posted: Thu Jul 03, 2003 3:07 am
by zelot1980_vn
Hi, All
I have a form which contains an array checkboxes. Examples:

<form method ="post" name="form1" id="form1">
<input type="checkbox" name="object[]" id="object[]" value="1">
<input type="checkbox" name="object[]" id="object[]" value="2">
</form>

I using PHP get value of array checkboxes. However, I want to check data of array checkboxes
by javascript. Example:

<script language="jscript">
function CheckData() {
var Form1 = document.forms['form1'].object
var ok = 0
for (i=0;i<Form1.object.length;i++)
{
if (Form1.object.checked) ok = 1
return true
}

if ( ok==0) {
alert("Data invalid")
return false
}
}
</script>


Is it the fact that Javascript desn't understand the [] at the end of the name's checkbox.
Javascript errors "object.length is null or not an object". Unfortunately I need the [] there
as they are to be processed by some php when I submit the form.

Thanks for all your help

Posted: Thu Jul 03, 2003 3:11 am
by []InTeR[]
You can change the ID to 'object1' and 'object2' etc...
And then do a findObjectById on the id?

Posted: Thu Jul 03, 2003 3:57 am
by twigletmac
Moved to Client Side 'cause it's a question about Javascript.

Mac

Posted: Thu Jul 03, 2003 4:10 am
by patrikG
If you leave the [] out of the form-field ID, you'll be fine (leave them in the name, though).

Code: Select all

<form method ="post" name="form1" id="form1">
<input type="checkbox" name="object&#1111;]" id="object" value="1">
<input type="checkbox" name="object&#1111;]" id="object" value="2">
</form>
Just another thing - I am not sure whether your form-field name "object" isn't a reserved keyword. I would give it a more descriptive name such as "checkBoxGender".

Checking if checkboxes have a value:

Code: Select all

function checkBoxValue(item)
	&#123;
	for(i=0;i<document.getElementById(""+item+"").length;i++)
		if(document.getElementById(""+item+"")&#1111;i].checked)
			return document.getElementById(""+item+"")&#1111;i].value;
	&#125;
I hope now Bob's your uncle again :)

Posted: Thu Jul 10, 2003 5:33 am
by gurjit
CHANGE

var Form1 = document.forms['form1'].object

TO


var Form1 = document.form1['object[]']