开发者

JS radio validation from a PHP $_POST form

开发者 https://www.devze.com 2023-02-09 14:44 出处:网络
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 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.


My recomendation would be to use http://pear.php.net/package/HTML_QuickForm

0

精彩评论

暂无评论...
验证码 换一张
取 消