简体   繁体   English

php表单上的单选按钮的javascript验证问题

[英]Issues with javascript validation of radio buttons on php form

This is the code for the php file containing the form with radio buttons: 这是包含带有单选按钮的表单的php文件的代码:

<?php
    while($r7 = mysql_fetch_array($rt3)){
        $name=$r7["name"];  
        $s=$r7["question"]; 

        echo "
        <div>$s</div>

        <form name='Tester' method='post' onSubmit='return RegValidate(this);' action='quest.php' >
        <input type='radio' name='w1' value='1'>1<br>
        <input type='radio' name='w1' value='2'>2<br>
        <input type='radio' name='w1' value='3'>3<br>



        ";
        }
        echo" <input  name='Submit' value='Tester' type='submit' />
        </form>";

?>

The $name and $q are derived from the database using a mysql query. $ name和$ q是使用mysql查询从数据库派生的。 This works fine. 这很好。 I have used the following javascript code so far: 到目前为止,我已使用以下javascript代码:

function RegValidate(Tester) 
 {

 if($('#w1').not(':checked'))
{
   alert('Radio not checked');
   return false;
}

}

But with this code, I continue to get the error message, and I am not able to move on even though I have selected a radio button. 但是使用此代码,我继续收到错误消息,即使选择了单选按钮,也无法继续操作。

The while loop produces several sets of radio buttons, as $q, gets the question from the database and posts it on the page along with 3 radio buttons. while循环产生几组单选按钮,例如$ q,从数据库中获取问题并将其与3个单选按钮一起发布到页面上。 Each question $q, has the 3 radio buttons in the above, hence the reason for the $name. 每个问题$ q在上面都有3个单选按钮,因此是$ name的原因。

How do I validate this form with javascript. 如何使用javascript验证此表单。 NB. 注意 The form will only contain radio buttons. 该表格将仅包含单选按钮。

you have an error, your input doesn't have ID or CLASS, so add to all of the input radio class='w1' and try the next code: 您遇到错误,您的输入没有ID或CLASS,因此将其添加到所有输入单选电台class='w1'然后尝试下一个代码:

 if ($(".w1 option:selected").length<1)
     alert ('nothing selected');

also take a look to this post: Check if option is selected with jQuery, if not select a default 也看一下这篇文章: 检查是否使用jQuery选择了选项,如果没有选择默认选项

do these things: 做这些事情:

      <input type='radio' class='w1' name='w1' value='1'>1<br>
      <input type='radio' class='w1' name='w1' value='2'>2<br>
      <input type='radio' class='w1' name='w1' value='3'>3<br>

And in js: 在js中:

Latest edit: 最新编辑:

  if ( $(':radio[class=w1]').attr('checked') != 'checked' ) {
    alert('Radio not checked');

}
function RegValidate(Tester) {
    if ($(":radio[name=w1]:checked").toArray().length == 0) {
        alert('nothing selected');
        return false;
    }
}​

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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