简单的JavaScript复选框验证 [英] Simple JavaScript Checkbox Validation

查看:128
本文介绍了简单的JavaScript复选框验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常用PHP工作,所以很遗憾没有一些基本的JS原则。这就是我想要完成的 - 我在这个主题上看到了很多帖子,但它们通常超出了我的需要。

I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.

这是我的表单:

 <input type="checkbox" name="checkbox" value="check"  />
 <input type="submit" name="email_submit" value="submit" onclick="----??----"  />

复选框是一个简单的我同意。我希望提交按钮被按下,只有在选中该复选框时才会提交。

The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.

以下是事情:我想要一个简单的,作弊的方法 - 没有方法 - 这种形式只是一些内联代码(假设它不会太长?)。这不是一个公共页面,我只需要用这种验证方式快速而简单的事情。如果未选中,它会抛出alert();如果它被选中,它将通过php提交并且照常进行。

Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.

推荐答案

您可以使用:

 if(!this.form.checkbox.checked)
{
    alert('You must agree to the terms first.');
    return false;
}

(demo page).

<input type="checkbox" name="checkbox" value="check"  />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}"  />




  • 返回 false 从内联事件处理程序将阻止默认操作发生(在本例中,提交表单)。 布尔运算符

  • 是提交按钮,因为它是事件处理程序附加到的元素。

  • .form 是提交按钮的形式。

  • .checkbox 是表单中名为checkbox的控件。
  • >
  • .checked 如果复选框处于选中状态,则为true;如果复选框处于未选中状态,则为false。

    • Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
    • ! is the Boolean NOT operator.
    • this is the submit button because it is the element the event handler is attached to.
    • .form is the form the submit button is in.
    • .checkbox is the control named "checkbox" in that form.
    • .checked is true if the checkbox is checked and false if the checkbox is unchecked.
    • 这篇关于简单的JavaScript复选框验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆