简体   繁体   中英

Rails simple form input show/hide

I'm using the ancestry gem in order to create categories and subcategories(parent, child, sibling). Then I have a select input inside a simple form:

<div class="form-group">
  <%= f.input :parent_category_id, collection: @categories, label: "Category", as: :grouped_select, group_method: :children, include_blank: true, input_html: { id: 'first-dropdown' } %>
</div>

I populate the above input with the parent categories:

@categories = Category.where(ancestry: nil)

And when I select a category in the above input the subcategories appear in the input below. If the category has no subcategories then the input is empty.

<div class="form-group">
  <%= f.input :category_id, label: "Subcategories", :collection => [], :label_method => :name, :value_method => :id, required: true, input_html: { multiple: true, id: 'second-dropdown' } %>
</div>

$('#first-dropdown').on('change', function() {
    $.ajax({
        url: 'categories/select_item?category_id=' + $(this).val(),
        dataType: 'json',
        success: function(data) {
            let childElement = $('#second-dropdown');
            childElement.html('');
            data.forEach(function(v) {
                let id = v.id;
                let name = v.name;
                childElement.append('<option value="' + id + '">' + name + '</option>');
            });
        }
    });
});

Everything works just fine with this setup. But now I would like to add a feature which I don't know how to. I want the second input to be initially hidden. And I want to show the second input if subcategories exist and hide the second input if subcategories don't exist. Any ideas how to implement this?

this could work...

    success: function(data) {
        let childElement = $('#second-dropdown');             
        childElement.toggle(Array.isArray(data) && data.length > 0)
        ...

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