简体   繁体   English

使用simple_form基于无线电选择隐藏/显示字段

[英]Hiding/Showing Fields Based On Radio Selection With simple_form

I have a form where I need the user to select (with radio buttons) an option that will determine the next form field beneath it. 我有一个表单,我需要用户选择(带有单选按钮)一个选项,该选项将确定它下面的下一个表单字段。 In this case, their post can be a post or a revision of a post. 在这种情况下,他们的帖子可以是帖子,也可以是帖子的修订版。 Thus, selecting 'post' will show a title field (to name the post) and selecting 'revision' will show a select list of existing posts to choose from (the title will be inherited). 因此,选择“帖子”将显示标题字段(以命名帖子),选择“修订”将显示现有帖子的选择列表(标题将被继承)。

_form.html.erb _form.html.erb

<!--Form inputs-->

<%= f.collection_radio_buttons :is_revision, [[false, 'Post'] ,[true, 'Revision']], :first, :last %>
<%= f.input :revision_id, collection: @originals, :input_html => {:id => 'revision'} %>
<%= f.input :title, :input_html => { :maxlength => '50', :placeholder => 'Title', :id => 'title'} %>

<!--Javascript-->

<script type="text/javascript">
$('input[name="post[is_revision]"]').on("change", function(){
    if ( $("#post_is_revision_true").attr("checked")){
        $("#title").hide();
        $("#revision").show();
    }
    if ( $("#post_is_revision_false").attr("checked")){
        $("#revision").hide();
        $("#title").show();
    }
});
</script>

I should mention that this works fine when hiding and showing one field, yet when selecting the other radio button nothing changes. 我应该提到的是,当隐藏和显示一个字段时,此方法工作正常,但是在选择另一个单选按钮时,则保持不变。 I feel the logic is correct (although I'm not the strongest with JS) but I can't seem to get this. 我觉得逻辑是正确的(尽管我不是JS最强的人),但我似乎无法理解这一点。

EDIT: I made a few jQuery errors. 编辑:我犯了一些jQuery错误。 Also, here is a jsFiddle example 另外, 这是一个jsFiddle示例

Try this. 尝试这个。

$('input[name="post[is_revision"]').change(function() {
    var selected = $('input:checked[name="post[is_revision]"]').val();
    if(selected == 'revision') {
        $('#title').hide();
        $('#revision').show();
    } else if(selected == 'new_post') {
        $('#revision').hide();
        $('#title').show();
    }
});

Another way to do it, smaller but more confusing: 另一种方法,更小但更令人困惑:

$('input[name="post[is_revision"]').change(function() {
    var is_revision = $('input:checked[name="post[is_revision]"]').val() == "revision";

    $('#title').toggle(!is_revision);
    $('#revision').toggle(is_revision);
});

If one will always be selected first, you could condense it to this: 如果将始终首先选择一个,则可以将其压缩为:

$('input[name="post[is_revision"]').change(function() {
    $('#title').toggle();
    $('#revision').toggle();
});

Or for kicks and giggles and slides: 或用于踢腿,咯咯笑和幻灯片:

$('input[name="post[is_revision"]').change(function() {
    $('#title').slideToggle();
    $('#revision').slideToggle();
});

Comment if you have problems with any. 如果您有任何疑问,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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