简体   繁体   中英

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. My knowledge in javascript is very basic.

Thanks

You had a little typo in your focus code (you typed forms instead of 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

<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. If the checkbox is check then you submit the form.

(also added http:// on the href attribute)

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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