Home Disable and enable with checkbox and simple form gem
Reply: 1

Disable and enable with checkbox and simple form gem

rld
1#
rld Published in 2018-01-10 18:30:41Z

I'm trying to disable and enable action with checkbox on the post form. And I don't know much about javascript or JQuery. And I'm trying to do this action a lot and I don't how to do it, I'm programming alone.

So if anyone could help me with this, I will appreciate! I'm using a Rails 4.2.8 and jquery-rails-4.3.1 versions.

my form: 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:"

I'm trying to put this on the fileapp/assets/javascript/_form.coffee it's alright or I need to put on another file?

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

This field published_at it's a date time. So I think now I need to put some array, the id's generated it's likeid="post_published_at_1i" and until id="post_published_at_5i"

luisenrike
2#
luisenrike Reply to 2018-01-10 19:25:25Z

If I understood you right, the only way of doing that is with 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;"

That will create something like the HTML part below, so, you just need to add the javascript to your page and maybe tweak it a little bit.

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>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.547408 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO