简单形式的条款和协议复选框

时间:2014-08-07 12:54:25

标签: javascript jquery ruby-on-rails ruby ruby-on-rails-3

我正在努力实现一些非常简单但却无法理解的事情。我只是希望用户选择条款和条件,而不能在不检查的情况下继续前进。我决定在客户端验证中这样做。

查看 - 复选框

<div class="fl">
    <input type="checkbox" id="checkbox" />
</div>
<div class="agree-txt">
    <span>I agree to <a href="#">Terms and Conditions</a>.</span>
</div>

查看 - 提交按钮

<%= f.button :submit, "Submit", :class=>"big-blue-btn" %>
    <a href = "#" class="text-link"> Sign Up as a User</a>
</li>

JS

$function validateCheckbox() {
    if ($('#checkbox').attr('checked')) {
        alert("you have to accept the terms first");
    }
});

请让我知道我是如何实现同样的目标,我知道我错过了一些非常小但无法找到的东西。

5 个答案:

答案 0 :(得分:1)

if ($('#checkbox').is(':checked'))

表示js -

$(document).ready(function () {
    $(document).on('click', '.big-blue-btn', function () {
        if (validateCheckbox()){
            ... do your submit code ....
        }
    });
});

function validateCheckbox() {
    if (!$('#checkbox').is(':checked')) {
        alert("you have to accept the terms first");
        return false;
    }else{
        return true;
    }
}

就这种类型的onclick事件而言,我会给你的按钮一个ID并使用它。

答案 1 :(得分:1)

您不应该使用类型为提交的按钮,因为如果您这样做,即使用户不满足特定条件,也会提交表单。

答案 2 :(得分:0)

诀窍是阻止表单提交,这是通过事件对象上的preventDefault()方法完成的。最好在表单提交上触发事件触发器,而不是单击按钮。这是因为可以通过点击文本字段中的输入来提交表单,而不仅仅是单击提交按钮。

# view.html.erb
<%= form_for my_object, html: {id: 'signup-form'} do %>
  ...
<% end %>


/* signup.js */
jQuery(function(){
  $('#signup-form').on('submit', function(event) {
    if(!$('#checkbox').attr('checked')) {
      showTermsAndConditionsErrorMessage();
      event.preventDefault();
    }
  });
});

答案 3 :(得分:0)

我最终以正常的轨道方式做到了。发布它可能会对将来有所帮助。

将此添加到我的用户模型

validates :terms_of_service, acceptance: true

在视图中

<%=f.check_box :terms_of_service %>

您不需要在数据库中包含此字段,rails默认提供此字段。请务必在模型中的attr_accessible中提及terms_of_service,否则会引发质量对齐错误。

答案 4 :(得分:-1)

试试这个。

var atLeastOneIsChecked = $('#checkbox :checkbox:checked').length > 0;

我的上述答案是错误的尝试这个。

if($("#checkbox-1").prop('checked') == true){
//do something
}