Forum Moderators: open

Message Too Old, No Replies

Need help for combining html, php and javascript

         

svanlieshout

10:30 am on Feb 25, 2006 (gmt 0)

10+ Year Member



Hi,

I have a problem, which I can't solve.

I have a form in HTML. In this form there can be 1 or more checkboxes, depending on how many records are in the MySQL server.

These checkboxes have the same name but each checkbox has a different value. To pass these values to PHP, I need to add '[]' at the end of the name.

So far so good.

Before I let this send to the server and PHP, I want to do some data verification in Javascript. I want to check if one or more checkboxes are checked.

With the code I have so far, this works for 2 or more checkboxes. With 1 checkbox and this one is checked, I still get the alert "No order specified". It seems that an array with 1 value in it, is not recognized.

See the code:

function doSubmit(){

var form = document.forms[0];
var checkbox_choices=0;

for(i=0;i<form["order[]"].length;i++){
if(form["order[]"][i].checked){
checkbox_choices=checkbox_choices+1;
}
}

if(checkbox_choices==0) {
alert('No order specified!');
return false;
}
}

in the body:

<input type=checkbox name=order[] value=<php echo"$row[id]";?>>

What I'm doing wrong?

Bernard Marx

1:13 pm on Feb 25, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It's like this. If there is a single checkbox, form["order[]"] returns a ref to that checkbox, not to a collection with 1 member - as you are coding for.

Either
1) Take that into account in the function.
or
2) Use document.getElementsByName("order[]")
- The W3C DOM collection methods always return a collection, even if it is length 1 or zero. This makes life easier for you here because the cases where you have only one box, or even no boxes at all, are automatically taken care of without error.

PS You don't need a counter (checkbox_choices) in your function. Just return true when you find a checked checkbox, and false at the end as a default.

svanlieshout

8:12 am on Feb 26, 2006 (gmt 0)

10+ Year Member



Thank you for your reply.

It has helped me solving my problem. Everything is working now.