help use the array checkbox in javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
zelot1980_vn
Forum Newbie
Posts: 2
Joined: Thu Jul 03, 2003 3:07 am
Location: programmer
Contact:

help use the array checkbox in javascript

Post 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
[]InTeR[]
Forum Regular
Posts: 416
Joined: Thu Apr 24, 2003 6:51 am
Location: The Netherlands

Post by []InTeR[] »

You can change the ID to 'object1' and 'object2' etc...
And then do a findObjectById on the id?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Moved to Client Side 'cause it's a question about Javascript.

Mac
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post 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 :)
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

Post by gurjit »

CHANGE

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

TO


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