【问题标题】:Radio button and having a text box validation Ruby on Rails单选按钮和文本框验证 Ruby on Rails
【发布时间】:2016-05-14 01:14:27
【问题描述】:

这是我目前的设置:

<input id="demographics_questionary_gender_male" name="demographics_questionary[gender]" type="radio" value="Male"> Male
<input id="demographics_questionary_gender_gender" name="demographics_questionary[gender]" type="radio" value="Female"> Female
<input id="demographics_questionary_gender_male" name="demographics_questionary[gender]" type="radio" value="Other"> Other
<input id="other_gender_value" name="other_gender[value]" size="30" type="text">

这将产生三个单选按钮(男、女、其他)。如果选择了“其他”单选按钮,还会出现一个文本框。

我的问题涉及如果选择了“其他”单选按钮,如何验证文本框是否已填写。

目前,我在控制器中检查是否选择了另一个单选按钮,如果是,那么我会将存储的值更改为“其他”文本框中设置的值。但是,我真的不知道如何验证文本框。我知道如何通过验证模型中是否设置了值来验证单选按钮是否被选中,但不知道如何确保用户已将数据输入到“其他”文本框中。

这是来自控制器的代码的 sn-p:

if @demographics_questionary.gender == 'Other'
    @other_gender = params[:other_gender]
    if @other_gender[:value].nil?
        @demographics_questionary.gender  = @other_gender[:value]
    else 
        @demographics_questionary.gender  = 'Not Set'
    end
 end

如您所见,如果选择了“其他”单选按钮并且“其他”文本框为空,我目前只是将其设置为“未设置”。但是,选择按钮处理数据时执行此代码。理想情况下,如果选择了“其他”单选按钮,我希望在视图页面上完成验证,这样会阻止用户继续前进,直到填写文本框。这样一来,当它甚至到达控制器方法时,就不需要进行此检查了。

但我再次对建议的任何其他方法持开放态度。

我认为这可以通过 JavaScript 或 jQuery 完成,但我不确定如何。

哦,是的,所以视图中的所有这些代码都位于一个表单字段中:

<% form_for(@demographics_questionary) do |f| %>
  <%= f.error_messages :header_message => "Please do not skip any of the questions." %>
  /* Code for radio buttons */
  <%= f.submit 'Next' %>   

 <%end%>

请注意,单选按钮代码位于 form_for 中。一旦提交按钮被触发,它将执行控制器中的方法。如果您要使用 JavaScript/jQuery,您将如何将函数附加到提交按钮?

这是当前页面:

http://otoplusvn.com/TherapistSurvey/demographics_questionaries/new 用于关于性别的问题 2。

有什么建议吗?我很感激,谢谢 德里克

【问题讨论】:

    标签: javascript ruby-on-rails jquery-validate radio-button


    【解决方案1】:

    你可以添加依赖规则,像这样:

    $('#register_form').validate({rules: {
         'other_gender[value]': {
           required: {
             depends: function(element) {
               return $("input[name=demographics_questionary[gender]]:checked").val() == "Other"
             }
           }
         }
    } });
    

    这将需要文本框,仅当所选选项为“其他”

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 2012-12-19
      • 1970-01-01
      • 2011-05-09
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多