简体   繁体   English

Javascript / Html中的复选框

[英]Checkbox in Javascript/Html

<script type="text/JavaScript">
    function checkForm(form)
    {
        if(!form.terms.checked){
        alert("Please indicate that you accept");
        forms.terms.focus();
        return false;
    }
    return true;

    }
</script>

<form onsubmit="return checkForm(this);" action="www.google.com">
<p><input type="checkbox" name="terms"> I accept</p>
<p><input class="button" type="submit" value="Continue" ></p>
</form>

Hello I'm trying to add a checkbox that you have to check in order to continue. 您好我正在尝试添加您必须检查的复选框才能继续。 It pops op correctly when you click on the button without checking the box; 当您单击按钮而不选中该框时,它会正确弹出操作; however, it is still take you to the website. 但是,它仍然带你到网站。 I want to keep asking to check the box before taking the user to the website. 我想在将用户带到网站之前不断询问复选框。 Could you guys give me a hand? 你能帮我个忙吗? I try adding it after the return true between { } but it doesn't seems to work. 我尝试在{}之间返回true之后添加它但它似乎不起作用。 My knowledge in javascript is very basic. 我在javascript中的知识非常基础。

Thanks 谢谢

You had a little typo in your focus code (you typed forms instead of form ). 您的焦点代码中有一点错字(您键入的是forms而不是form )。 Here's the correct code. 这是正确的代码。

function checkForm(form)
{
    if(!form.terms.checked){
        alert("Please indicate that you accept");
        form.terms.focus(); // corrected "form" instead of "forms"
        return false;
    }
    return true;
}

Fiddle 小提琴

I think the problem comes with the focus on the input checkbox. 我认为问题在于关注输入复选框。 Please change your Javascript code to 请将您的Javascript代码更改为

<script type="text/JavaScript">
function checkForm(form)
  {
     if(!form.terms.checked){
       return false;
      }
       return true;
  }

You can change the type of the button from submit to button and fire the evaluation function on the click event. 您可以将按钮的类型从提交更改为按钮,并在click事件上触发评估功能。 If the checkbox is check then you submit the form. 如果选中该复选框,则提交表单。

(also added http:// on the href attribute) (还在href属性上添加了http://)

<script type="text/JavaScript">
function checkForm(button)
{
    var form = button.form;
    if(!form.terms.checked)
    {
        alert("Please indicate that you accept");
        form.terms.focus();         
    }
    else
    {
        form.submit();
    }

}
</script>

<form action="http://www.google.com">
<p><input type="checkbox" name="terms"> I accept</p>
<p><input class="button" type="button" value="Continue" onclick="checkForm(this)" ></p>
</form>

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

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