使用jquery验证单选按钮?

时间:2011-01-07 08:34:49

标签: jquery

我试图通过使用jQuery来验证Struts2中的单选按钮。任何人都可以帮我这个吗?

2 个答案:

答案 0 :(得分:0)

试试这个:

   if(($('input:radio:selected', this).length > 0))
   {
      // do stuff
   }

答案 1 :(得分:0)

以下是单选按钮检查的基本概念......

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('#sendform').click(function(){
                    // at the beginning, set IsSelected to false
                    var isSelected = false;
                    var value = '';
                    $('[name=gender]').each(function(index){
                        if($(this).attr('checked'))
                        {
                            isSelected = true;
                            value = $(this).attr('value');
                        }                        
                    })
                    if(!isSelected) alert('Radio button is not selected');
                    else alert('Selected value: '+value)

                    //prevent form from submiting
                    return false;
                })
            })
        </script>
    </head>
    <body>
        <form action="youraction.php" >
            <fieldset>
                <legend>Select your gender</legend>
                <p><input type="radio" name="gender" value="male" >male</p>
                <p><input type="radio" name="gender" value="female" >female</p>
                <input type="submit" value="Send" id="sendform">
            </fieldset>
        </form>
    </body>
</html>