简体   繁体   English

检查是否已选中复选框

[英]Check if checkbox is checked

Why does the following code not work? 为什么以下代码不起作用?

Example: http://jsfiddle.net/ZZe5X/18/ 示例: http //jsfiddle.net/ZZe5X/18/

$('.submit').submit(function () {
    e.preventDefault()
    if ($('input[type="checkbox"]').is(':checked')) {
        alert('ok')
    } else {
        alert('no')
    }
})

Okey: 好:

  1. you are missing the event: $('.submit').submit(function () { should be $('.submit').submit(function (e) { 您缺少该事件: $('.submit').submit(function () {应该是$('.submit').submit(function (e) {
  2. The button is missing a type="submit" and it should be inside the form element. 该按钮缺少type =“ submit”,它应该在form元素内。
  3. The Form element is missing the class submit Form元素缺少类submit

this should work: http://jsfiddle.net/voigtan/ZZe5X/26/ 这应该工作: http : //jsfiddle.net/voigtan/ZZe5X/26/

You don't have a submit button in a form with the class submit , so your submit event handler never executes. 你不必与类的表单提交按钮submit ,所以您提交的事件处理程序从不执行。 Add class="submit" to your form tag and change <button>Click me</button> to <input type="submit" value="Click me" /> and move it to before your </form> tag. class="submit"添加到您的表单标签,然后将<button>Click me</button>更改为<input type="submit" value="Click me" />并将其移至</form>标签之前。

Please try this. 请尝试这个。

   $('.submit').submit(function () {

        if ($('input[type="checkbox"]').is(':checked')) {
            alert('ok');
        } else {
            alert('no');
        }
      return false;
    })

看到这个: http : //jsfiddle.net/ZZe5X/16/

  1. You didn't have a submit class 您没有提交课程
  2. You had .submit() set on a button, it needs to be .click 您在按钮上设置了.submit(),它需要是.click
  3. You weren't iterating through each checked box, which is what I assume you wanted to be doing. 您并没有遍历每个复选框,这是我认为您想做的。

See the tweaked example: http://jsfiddle.net/ZZe5X/33/ 请参阅经过调整的示例: http : //jsfiddle.net/ZZe5X/33/

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

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