简体   繁体   中英

JS radio validation from a PHP $_POST form

I have a form that has a variable number of radio buttons in it:

<input id='create' name="post[]" type="radio"  value="<? echo $newphrase; ?>" />

I wish to validate it to make sure that at least one button is selected. I have this code:

 function valbutton(thisform) {
 myOption = -1;
 for (i=thisform.post.length-1; i > -1; i--) {
 if (thisform.post[i].checked) {
 myOption = i; i = -1;
 }
}
if (myOption == -1) { 
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.myradiobutton[myOption].value);
thisform.submit(); // this line submits the form after validation
}             

This works for the validation , but then the $_POST values are not set. theoretically this line:

for (i=thisform.post.length-1; i > -1; i--) {
if (thisform.post[i].checked) {

should read like:

for (i=thisform.post[].length-1; i > -1; i--) {
if (thisform.post[][i].checked) {

But that obviously doens't work as it errors.

Solved using Ed Daniels idea of setting "CHECKED" to the radio button. Even though there are a variable number of buttons, it will just 'check' the last one generated, which is good enough in my case.

I'm not sure why you're using the array syntax (name="post[]") for a set of radio buttons. You're only ever going to get one value back at the server, that of the checked radio button.

(For a bunch of checkboxes, where any combination might be checked, it would make sense.)

name="post" in the radio button, and $_POST['post'] in your PHP, should work fine. I suspect that it will also fix your Javascript problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM