简体   繁体   中英

How to dynamically show Rails fields based on a boolean field's state?

In a Rails 3 app using Jquery, I'm trying to dynamically show/ hide form elements, based on whether a boolean field is true or false.

At present my jquery function looks something like this:

$(function() {
    $('#boolean').change(function(){
        if ($(this).value == true) {
            $('.hidden-fields').show();
        } else {
            $('.hidden-fields').hide();
        }
    });
})

How do I correctly pass the boolean fields value into this function such that:

  1. the function is initialized on page load, and fields hidden/shown based on the value in the database; and
  2. the fields are toggled when the boolean is changed.

Sorry of this is a simple question. I'm trying to get to grips with javascript and really appreciate any pointers.

Thanks

Do you only have one element on your HTML page with an id of boolean? Because using #boolean will return the first one only. If you have many, you should use a class of boolean instead, and then use .boolean to reference all elements with that class.

But to your questions:

1) Your example code there will be run on page load and will automatically apply to all elements with a .boolean class (assuming you go that way). If you want to immediately hide or show elements because, say, a value in the DB is set to false , then you should do that when you're rendering your page in your ERB or HAML or whatever view.

2) If the element you're attaching this JS to is a select box or something that will have a change() function, then you're all set to go. If you're wondering if, when the DB changes, this view automatically changes its visibility, then that is something different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM