简体   繁体   English

基于单选按钮选择的字段切换,带有simple_form,haml和jquery

[英]Toggle fields based on radio button selection with simple_form, haml, and jquery

I have a radio button in my form. 我的表格中有一个单选按钮。 If true is selected, I would like to show an additional field. 如果选择true ,我想显示一个附加字段。 If false , I would like the additional field hidden. 如果为false ,我希望隐藏其他字段。 I have tried several possible solutions I found on SO but none seem to be working. 我已经尝试了几种在SO上找到的可能解决方案,但似乎都没有用。

In my form: 以我的形式:

%fieldset
  %legend
    Visa & Passport
  .form-group
    = f.input :work_visa, as: :radio_buttons, label: "Do you have a work visa?", collection: [['Yes', true], ['No', false]], checked: true, item_wrapper_class: 'radio-inline', wrapper_html: { id: 'work-visa'}
    = f.input :visa_exp_date, label: 'Visa Expiration Date', item_wrapper_class: 'form-inline', class: 'col-xs-4', wrapper_html: { id: 'work-visa-exp'}

At the bottom of the page: 在页面底部:

:javascript  
  $('#work-visa-exp').show();    
  $('input[type=radio]').on("change", function(){
    if($(this).prop('id') == "work-visa") {
      $('#work-visa-exp').toggle();
    }
  });

I am pretty sure the error is in my JS. 我很确定错误是在我的JS中。 If I comment out everything but $('#work-visa-exp').show(); 如果我注释掉$('#work-visa-exp').show(); and change .show() to .hide() , the field is hidden as expected. 和更改.show().hide()如所预期的字段隐藏。

Based on your description, you need a checkbox and not a radio button. 根据您的描述,您需要一个复选框,而不是一个单选按钮。

Please check below: 请检查以下内容:

 $(document).ready(function() { $('#work-visa-exp').hide(); $('input[type=checkbox]').on("change", function() { if ($(this).prop('id') == "work-visa") { $('#work-visa-exp').toggle(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" name="vehicle" id="work-visa" value=""> <input type="text" name="vehicle" id="work-visa-exp" value=""> 


If you are using other radio buttons (different kind of visas). 如果您使用其他单选按钮(不同种类的签证)。 Then you can try below. 然后,您可以在下面尝试。

With this one you have to check the value of the selected radio buttons and not the id. 使用此按钮,您必须检查所选单选按钮的值,而不是id。

 $(document).ready(function() { $('#work-visa-exp').hide(); $('input[type=radio]').on("change", function() { if ($(this).val() == "work-visa") { $('#work-visa-exp').show(); } else { $('#work-visa-exp').hide(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="radio" name="visa" value="work-visa"> Work Visa <input type="text" name="vehicle" id="work-visa-exp" value=""> <br /> <input type="radio" name="visa" value="other-visa"> Other Visa <br /> <input type="radio" name="visa" value="some-visa"> Some Visa <br /> 

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

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