【问题标题】:Checkbox validation in jquery [closed]jquery中的复选框验证[关闭]
【发布时间】:2012-11-05 20:36:57
【问题描述】:

我在表单上的选择复选框中需要帮助。我想显示一个警报,因为表单复选框未选中(仅)。我的代码:

<form action="index.php?page=contact&amp;send=ok" method="POST" id="form">
[...]
<label for="message">Checkbox:</label><input type="checkbox" id="checkbox" name="checkbox">           
<input type="submit" value="Send" onclick="testcheck()" />
</form>

<script type="text/javascript">
function testcheck()
{
    if (jQuery("#checkbox").prop("checked"))
        alert("first button checked");
    else
        alert("none checked");
}
</script>

【问题讨论】:

  • 不确定是什么问题。这是一个工作小提琴:jsfiddle.net/k2uhv
  • @Asad 如果您不确定问题出在哪里,请考虑添加jQuery("#submit").click(testcheck);
  • @MBJ 它甚至可以使用内联处理程序,所以我仍然没有看到问题:jsfiddle.net/jwmsu
  • 我希望在取消选中复选框时不发送表单。

标签: jquery validation checkbox alert attr


【解决方案1】:

这段代码应该可以工作:

function testcheck()
{
    if (!jQuery("#checkbox").is(":checked")) {
        alert("none checked");
        return false;
    }
    return true;
}

这里是 HTML 代码:

<input type="submit" value="Send" onclick="return testcheck()" />

return false 将停止执行默认操作(表单提交)

【讨论】:

  • 差不多,我想在发送未选中的复选框之前阻止表单。未选中的复选框发送表单。
【解决方案2】:

FAngel 是对的,但我也会这样做:

<input type="submit" value="Send" id="testcheck" />

还有:

$("#testcheck").on('click', function() {
    if (jQuery("#checkbox").is(":checked")) {
        alert("first button checked");
    }
    else {
        alert("none checked");
    }
});

小提琴:http://jsfiddle.net/matthewbj/hU4UY/

【讨论】:

  • 那个js的问题是无论如何都会提交。您需要返回 false 和/或使用preventDefault
  • @Asad OP 没有提到需要这样的功能。
  • 我知道,只是想看看 OP 想要什么
【解决方案3】:

老兄,使用jQuery可以是三种方法。

它们是:.prop()、.is() 和 .attr()。

例如,我将演示这些代码:

function testcheck()
{
    if (jQuery("#checkbox").prop("checked")){
        alert("first button checked");
}
    else{
        alert("none checked");
}
}


function testcheck()
{
    if (jQuery("#checkbox").is(":checked")){
        alert("first button checked");}
    else{
        alert("none checked");
}


function testcheck()
    {
        if (jQuery("#checkbox").attr("checked")=="checked"){
            alert("first button checked");}
        else{
            alert("none checked");}
    }

http://api.jquery.com/prop/

再见,晚上好

【讨论】:

    【解决方案4】:

    这应该可行:

    function testcheck(e)
    {
        if (jQuery("#checkbox").prop("checked")){
            alert("first button checked");
        }
        else{
            alert("none checked");
            e.preventDefault();
            return false;
        }
        return true;
    }
    
    jQuery("#submit").click(testcheck);
    

    我猜你遇到的问题是提交仍然进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多