【问题标题】:How to validate checkboxes on submit button?如何验证提交按钮上的复选框?
【发布时间】:2015-12-02 23:27:46
【问题描述】:

我有一个简单的问题,但我尝试了很多东西,但它们没有按我的预期工作。

问题: 1. 一些复选框,类如“a”、“b”、“c”,但 id 不同。 2. 在按钮单击时,我尝试验证是否仅选中了一个复选框。 3. 我只知道复选框类(通用元素)

我的代码:

$('#submit').click(function() {
    var matches = [];
    var items = document.getElementsByClassName('1'); //??? if the items is null?

    for (var i = 0; i < items.length; i++){
        matches.push({id:items[i].id, value:items[i].value});
    }

    if((matches[0].id != matches[1].id) &&(matches[0].value == matches[1].value))
        alert("ERROR!!!");
});

请告诉我解决该问题的最佳方法

【问题讨论】:

  • 你能用一些示例 html 更新你的问题吗?
  • “点击按钮时,我会尝试验证只有一个复选框被选中”——你为什么首先使用复选框而不是单选按钮?
  • 因为我必须@昆汀
  • 你的意思是表单提交,而不是按钮点击右键.....
  • getElementsByClassName('1'); 类名不应以数字开头 stackoverflow.com/a/449000/822711 另外,既然您使用的是 jQuery,那么使用 jQuery 选择它们有什么问题?

标签: jquery validation checkbox


【解决方案1】:

您正在使用 jQuery。您希望使用类名为“1”的复选框,几乎就像它们是单选按钮一样,如果选中多个复选框,则会发出错误警报。您的 classname is invalid,很可能您应该在表单提交时检查此内容,但这是您要查找的代码。

$('#submit').click(function() {
    if ($('.1:checked').length > 1) alert('error');
});

...我想在这种情况下您还想阻止按钮提交表单:

$('#submit').click(function(e) {
    if ($('.1:checked').length > 1) {
        e.preventDefault();
        alert('error');
    }
});

【讨论】:

  • 工作得很好。谢谢
【解决方案2】:
查看此代码可能会对您有所帮助!
<input type = "checkbox" class = "a ownClass" id = "one"></input>
<input type = "checkbox" class = "b ownClass" id = "two"></input>
<input type = "checkbox" class = "c ownClass" id = "three"></input>
<input type = "button" id = "submit" value = "submit"></input>


  (function(){
        $("#submit").click(function(){
        var checked = [];
        $(".ownClass").each(function(currIndex, val){
        if($(this).is(':checked')){
            checked.push(this.id);
        }

     })
    console.log(checked);
  });
}());

【讨论】:

  • 谢谢。但就我而言,@Popnoodles anserw 是最好的:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 2018-02-19
相关资源
最近更新 更多