【问题标题】:Disable and enable with checkbox and simple form gem使用复选框和简单表单 gem 禁用和启用
【发布时间】:2018-01-10 18:30:41
【问题描述】:

我正在尝试使用帖子表单上的复选框禁用和启用操作。 而且我对javascript或JQuery知之甚少。 我经常尝试做这个动作,但我不知道如何做,我一个人编程。

因此,如果有人可以帮助我,我将不胜感激! 我使用的是 Rails 4.2.8 和 jquery-rails-4.3.1 版本。

我的表格:app/views/posts/_form.html.slim

 = simple_form_for(@post, :html => { :multipart => true }) do |f|    = f.input :publish,
             label: "Publish?",
             as: :boolean,
             label_html: { class: "publish-check" },
             input_html: { checked: false },
             remote: true    = f.input :published_at, disabled: true, hint: 'You cannot publish your post.',label: "Publish Post at:"

我正在尝试将其放入文件app/assets/javascript/_form.coffee 没关系,或者我需要放入另一个文件?

$(document).on "turbolinks:load", ->
  $checkbox = $('[id^="post_publish"]')
  $select = $('.post_published_at')
  $checkbox.change (e) ->
    $select.prop 'disabled', !$checkbox.is(':checked')
    return
  return

此字段已发布_这是一个日期时间。 所以我想现在我需要放一些数组,生成的 id 就像id="post_published_at_1i" 直到id="post_published_at_5i"

【问题讨论】:

    标签: javascript jquery ruby-on-rails-4 twitter-bootstrap-3 simple-form


    【解决方案1】:

    如果我理解正确的话,唯一的方法就是使用 javascript:

    = simple_form_for(@post, :html => { :multipart => true }) do |f|
       = f.input :publish, label: "Publish?", as: :boolean, input_html: { checked: false }
       = f.input :published_at, label: "Publish Post at", style: "visibility: hidden;"
    

    这将创建类似于下面的 HTML 部分的内容,因此,您只需将 javascript 添加到您的页面并进行一些调整即可。

    window.addEventListener('load', function() {
      document.getElementById('post_publish').addEventListener('change', function() {
        var input = document.getElementById('post_published_at')
        if (this.checked) {
          input.style.visibility = 'visible';
          input.disabled = false;
        } else {
          input.style.visibility = 'hidden';
          input.disabled = true;
        }
      });
    });
    <form id="new_post" action="/post" method="post">
      <input id="post_publish" type="checkbox">
      <label>Publish?</label>
      <input id="post_published_at" style="visibility: hidden;">
    </form>

    【讨论】:

    • 我现在只是在看,隐藏的方式不是很好的选择,最好使用显示:无,然后使用 javascript put display: block。因为如果未选中,我不希望提交字段 published_at 的任何值
    • 感谢您的回复@luisenrike,我编辑了代码以回复您的代码,因为我有一个错误,这里的内容太小了。我现在没有太多 javascript,我尝试的这段代码会引发错误。
    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多