验证条款和条件复选框

时间:2013-07-28 01:28:09

标签: jquery forms validation checkbox

这是我的 My JSFiddle

我试图在单击复选框时添加一个类,但我似乎无法弄清楚如何以适合我已有的代码的方式进行操作。

CODE:

  $(this).live("change keyup", function () {

  var checkbox = $('#termscons').prop(':checked');

  if (currid == "termcons") {

                if (checkbox == 'checked') {
                    infobox.html("Accepted!");
                    infobox.addClass('good');
                } else if (checkbox !== 'checked') {
                    infobox.html(replacehtml);
                    infobox.removeClass('good');
                }
            }  

         if ($('#termscons').next().hasClass('good')) {

            $("#sendbtn").css("display", "block");
        } else {
            $("#sendbtn").css("display", "none");

        }

3 个答案:

答案 0 :(得分:3)

首先,不要使用live,不推荐使用,而是使用on,例如

$(document).on('change', '#termscons', function(){
    if($(this).is(':checked')) {
        // checked, so you can add class, i.e.
        infobox.addClass('good');
        // other code
    }
    else {
        // not checked
        infobox.removeClass('good');
        // other code
    }
});

这也回答了如何根据class的状态添加/删除checkbox

DEMO.

答案 1 :(得分:0)

您正在尝试访问的:checked道具应该是checked 我从网站上复制了这个 http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html

  // First way
    $('#checkBox').attr('checked');
    // If using jQuery 1.6 or up use .prop() instead
    // Learn the difference between property and an attribute
    $('#checkBox').prop('checked');

    // Second way 
    $('#edit-checkbox-id').is(':checked'); 

    // Third way for jQuery 1.2
    $("input[@type=checkbox][@checked]").each( 
        function() { 
           // Insert code here 
        } 
    );
    // Third way == UPDATE jQuery 1.3
    $("input[type=checkbox][checked]").each( 
        function() { 
           // Insert code here 
        } 
    );

    // In his comment Andy mentions that the 3rd method
    // does not work in Firefox 3.5.2 & jQuery 1.3.2

我希望这可以帮助:)

答案 2 :(得分:0)

你有几个问题。工作jsfiddle

  1. 您绑定到所有文本框的焦点事件,然后在处理程序中,您尝试绑定到当前文本框的更改事件,期望您的复选框是文本框之一。)
  2. 您绑定了错误的事件以获取复选框。使用click
  3. 检查道具(“:已检查”)是错误的。请改用is

      $("#termscons").click(function(){
                var infobox = $(this).next();
                var checkbox = $(this).is(':checked');
    
                // we use this logic to check the subject
                if (checkbox) {
                    infobox.html("Accepted!");
                    infobox.addClass('good');
                } else {
                    infobox.html("");
                    infobox.removeClass('good');
                }
    });