onclick与jquery没有按预期工作

时间:2016-07-15 10:54:54

标签: javascript jquery asp.net

以下是示例代码..如果我注释掉脚本,它将在按钮单击时调用服务器端功能。以下代码中的错误是什么?

<form id="form1" runat="server">    
   <input type="checkbox" id="chb1" value="Hourly" />
   <input type="checkbox" id="chb2" value="Daily" />
   <input type="checkbox" id="chb3" value="Weekly" />
   <input type="checkbox" id="chb4" value="Monthly" />
   <input type="checkbox" id="chb5" value="Yearly" />

  <asp:Button Text="submit" runat="server" ID="btnSubmit" OnClick="btnSubmit_Click"/>
</form>
<div></div>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">

        var selectedcout = 0;

        var countChecked = function () {
            var n = $("input:checked").length;                
            $("div").text(n + (n === 1 ? "is" : "are") + "checked");
        };
        countChecked();

        $("input[type=checkbox]").on("click", countChecked);

</script>

1 个答案:

答案 0 :(得分:0)

您需要挂钩表单的submit事件,而不是提交按钮的click,以便您可以停止提交表单。试试这个:

var selectedcout = 0;

var countChecked = function() {        
    var n = $("input:checked").length;                
    $("div").text(n + (n === 1 ? " is " : " are ") + "checked");
};

countChecked();

$('#form1').on('submit', function(e) {
    e.preventDefault(); // stop the form submitting
    countChecked();
});