只有在使用jQuery单击任何复选框时,才应启用提交按钮

时间:2014-12-23 10:08:32

标签: javascript jquery checkbox

我面临以下问题;只有在单击任何复选框时才应启用提交按钮。使用jQuery我的代码是:

$(document).ready(function() {
    var the_terms = $("#pricingTierId");
    the_terms.click(function() {
        if ($(this).is(":checked")) {
            $("#submitBtn").removeAttr("disabled");
        } else {
            $("#submitBtn").attr("disabled", "disabled");
        }
    });
});
<c:if test="${fn:length(incentiveList) gt 0}">
    <input type='button' name="submit" id = "submitBtn" value='Submit Incentives' onClick='execute();' />
</c:if>

但是在复选框代码中我有以下

<td>
    <s:checkbox name="checkboxes[%{#stat.index}]" theme="simple" id="%{pricingTierId}"/>    
</td>

我的id属性被定义为id="%{pricingTierId}"所以我无法在jQuery函数中真正传递它,如上所示。请建议合适的方式

1 个答案:

答案 0 :(得分:2)

使用.prop()代替.attr()。从 jQuery 1.6 开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()检索属性。

将一个类添加到复选框,然后您可以使用该类(因为OP使用的是struts2 cssClass

<s:checkbox cssClass="yourClass" name="checkboxes[%{#stat.index}]" theme="simple" id="%{pricingTierId}"/>    

代码,您的代码也可以转换为单行

$('.yourClass').change(function() {
    $("#submitBtn").prop("disabled", this.checked == false);
});

如果你有多个复选框,至少应检查一个

$('.yourClass').change(function() {
    $("#submitBtn").prop("disabled", $('.yourClass').is(":checked") == false);
});

同时浏览.prop() vs .attr()