Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

javascript - 简单的JavaScript复选框验证(Simple JavaScript Checkbox Validation)

I usually work with PHP so sadly don't have some basic JS principles down.(我通常使用PHP,所以很遗憾没有一些基本的JS原则。)

This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.(这就是我想要完成的任务 - 我已经看过很多关于这个主题的帖子,但它们通常超出我的需要。) Here is my form:(这是我的表格:) <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.(我希望按下提交按钮,只有选中该复选框才会提交。) 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();(如果未选中,则会抛出alert();) if its checked it will submit via post through php and go on as normal.(如果它被检查它将通过邮件提交通过PHP并继续正常。)   ask by TheLettuceMaster translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use:(你可以使用:)

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}" /> Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).(从内联事件处理程序返回false将阻止发生默认操作(在这种情况下,提交表单)。) ! is the Boolean NOT operator .(是布尔NOT运算符 。) this is the submit button because it is the element the event handler is attached to.(this是提交按钮,因为它是事件处理程序附加到的元素。) .form is the form the submit button is in.(.form是提交按钮所在的表单。) .checkbox is the control named "checkbox" in that form.(.checkbox是该表单中名为“checkbox”的控件。) .checked is true if the checkbox is checked and false if the checkbox is unchecked.(如果选中该复选框,则为.checked ;如果未选中该复选框,则为false。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...