1

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

<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>
4

4 回答 4

10

此代码应该可以工作:

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将停止执行默认操作(表单提交)

于 2012-11-05T20:42:37.600 回答
4

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/

于 2012-11-05T20:44:35.773 回答
2

老兄,可以使用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/

再见,晚上好

于 2012-11-05T20:57:19.500 回答
0

这应该有效:

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);

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

于 2012-11-05T20:46:24.413 回答