开发者

What's wrong in this code? Why does it still give a MsgBox if the user selects or does not select the checkbox?

Where to modify this code

It still gives a msgbox whether I select the checkbox box or not ....

My code below will redirect to Google in both conditions: If the user selects the checkbox, then it will redirect to www.google.com, but if a user forgets to check the checkbox then it shows the message box with an OK button. When I click OK it should redirect to www.google.com.

I want

When a user forgets to check any of the checkboxes it should show a message box with an OK button and stay on the same page. Otherwise if the user selects any of the checkboxes then redirect to www.google.com.

What's wrong with this code?

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>

    <body>
        <form id="form1" runat="server">
            <div>
                <asp:CheckBox ID="CheckBox1" runat="server" />开发者_如何转开发
                <asp:CheckBox ID="CheckBox2" runat="server" />
            </div>
            <asp:Button ID="Button1" runat="server" OnClientClick ="ConfirmSelection(this.form)" Text="Button" />
        </form>
        <script type="text/javascript">
            function ConfirmSelection(frm)
            {
                for (i=0; i<=1; i++) {
                    //chkSubjectOfInterest is the id of your checkbox control

                    if (frm.elements[i].name.indexOf('chkSubjectOfInterest') !=-1)
                    {
                        if (frm.elements[i].checked)
                        {
                            return true
                        }
                    }
                }
                alert('You haven\'t selected an item yet!')
                return false
            }
        </script>
    </body>
</html>


You could use this JavaScript function:

<html>
<head>
<script type="text/javascript" language="javascript">
function checkboxChecked(){
    var checked=false;
    var allInputs = document.getElementsByTagName("input");
    for(var i=0; i<allInputs.length; i++){
         var chk=allInputs[i];
         if(chk.type == "checkbox"){
            if(chk.checked){
               checked=true;
               break;
            }
         } 
    }
    if(!checked)
        alert("You should check something!!");
    return checked;
}
</script>
</head>
<body>
<input type="checkbox" /><input type="checkbox" /><input type="checkbox" /><input type="checkbox" />
<br />
<asp:Button ID="Button1" runat="server" OnClientClick ="javascript:return checkboxChecked();" Text="Button" />
</body>
</html>

This works also with ASP.NET checkboxes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜