Rails 4 表单:基于单选按钮选择条件显示字段

2023-11-30

首先,如果这个问题很愚蠢,请原谅我,我刚刚开始了解 Rails,Javascript 和 jQuery 对我来说是一个全新的世界。

我发现了以下类似的问题,但根本不明白它们如何适用于我的情况:

  • 如果选中复选框则显示/隐藏 div
  • 根据所选的单选按钮检查隐藏的输入字段
  • 根据单选按钮选择显示表单字段

话虽这么说,这是我的问题。

在我的 Rails 4 应用程序中,我有以下 Rails 表单(我是NOT使用简单形式):

<div class="calendar_details">
  <%= f.label :target_relationship %>
  <%= radio_button_tag(:target_relationship, "B2C", :checked => true, :onclick=>"showMe('calendar_details_b2c')", {:class => "radio_button_target_relationship_b2C"}) %>
  <%= label_tag(:target_relationship, "B2C") %>
  <%= radio_button_tag(:target_relationship, "B2B", :onclick=>"showMe('calendar_details_b2b')", {:class => "radio_button_target_relationship_b2b"}) %>
  <%= label_tag(:target_relationship, "B2B") %>
</div>

<div class="calendar_details">
  <%= f.label :target_country %><%= f.country_select :target_country, ["United States"] %>
</div>

<div id="calendar_details_b2c">

  <div class="calendar_details">
  <%= f.label :target_gender %><%= radio_button_tag(:target_gender, "Female") %><%= label_tag(:target_relationship, "Female") %><%= radio_button_tag(:target_gender, "Male") %><%= label_tag(:target_relationship, "Male") %><%= radio_button_tag(:target_gender, "Both", :checked => true) %><%= label_tag(:target_relationship, "Both") %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_age_lower_limit %><%= f.select :target_age_lower_limit, (0..99) %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_age_upper_limit %><%= f.select :target_age_upper_limit, (0..99) %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_household_income_lower_limit %><%= f.select :target_household_income_lower_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_household_income_upper_limit %><%= f.select :target_household_income_upper_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
  </div>

</div>

<div id="calendar_details_b2b">

  <div class="calendar_details">
    <%= f.label :target_company_size %><%= f.select :target_company_size, ['Self-employed', '1-10 employees', '11-50 employees', '51-200 employees', '201-500 employees', '501-1,000 employees', '1,001-5,000 employees', '5,001-10,000 employees', 'More than 10,000 employees'] %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_industry %><%= f.select :target_industry, ['Art & Entertainment', 'Autos & Vehicles', 'Beauty & Fitness', 'Books & Litterature', 'Business & Industrial', 'Computer & Electronics', 'Finance', 'Food & Drinks', 'Games', 'Hobbies & Leisure', 'Home & Garden', 'Internet & Telecom', 'Jobs & Education', 'Law & Government', 'News', 'Online Communities', 'People & Society', 'Pets & Animals', 'Real Estate', 'Science', 'Shopping', 'Sports', 'Travel']  %>
  </div>

</div>

根据用户在第一个单选按钮(“B2C”或“B2B”)上检查的内容,我想显示calendar_details_b2c div, 或者calendar_details_b2b div.

我知道我需要隐藏两者divs,然后实现某种形式的条件,检查哪个单选按钮被选中,最后显示正确的div.

正如你所看到的,我尝试添加一个onclick选项和一些特定的类到我的单选按钮,但后来我陷入困境:我不知道如何构建正确的 js 函数,而且我不知道在哪里包含它(在.html.erb表单的文件,在应用程序的标题中,在application.js file?).

—————

UPDATE:根据 Ziv Galili 的回答,这是我现在所拥有的:

In app/assets/javascript/custom/calendars.js:

$(document).ready(function() {
    $('input[type=radio][name=calendar').change(function () {
      // first: hide all the divs
      $('#calendar_details_b2c').css("display","none");
      $('#calendar_details_b2b').css("display","none");

      // then get the div ID to show (I stored it in the "value" of the radio button)
      var fieldToShow = $(this).val();
      // now use jQuery selector and change the display setting of that field
      $("#" + fieldToShow).css("display","block");
    });
});

In application.js,我补充说//= require_tree ./custom在我的应用程序中考虑上述代码。

在我的表格所在的视图中(Calendars#New视图),我现在有:

<div class="calendar_details">
    <%= f.label :target_relationship, "Business relationship" %>
    <%= f.radio_button :target_relationship, "calendar_details_b2c", :checked => true %>
    <%= f.label(:target_relationship, "B2C") %>
    <%= f.radio_button :target_relationship, "calendar_details_b2b", :checked => false %>
    <%= f.label(:target_relationship, "B2B") %>
  </div>

  <div class="calendar_details">
    <%= f.label :target_country, "Country" %><%= f.country_select :target_country, ["United States"] %>
  </div>

  <div id="calendar_details_b2c">

    <div class="calendar_details">
    <%= f.label :target_gender, "Gender" %><%= radio_button_tag(:target_gender, "Female") %><%= label_tag(:target_relationship, "Female") %><%= radio_button_tag(:target_gender, "Male") %><%= label_tag(:target_relationship, "Male") %><%= radio_button_tag(:target_gender, "Both", :checked => true) %><%= label_tag(:target_relationship, "Both") %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_age_lower_limit, "Age / Lower limit" %><%= f.select :target_age_lower_limit, (0..99) %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_age_upper_limit, "Age / Upper limit" %><%= f.select :target_age_upper_limit, (0..99) %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_household_income_lower_limit, "Household income / Lower limit" %><%= f.select :target_household_income_lower_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_household_income_upper_limit, "Household income / Upper limit" %><%= f.select :target_household_income_upper_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
    </div>

  </div>

  <div id="calendar_details_b2b">

    <div class="calendar_details">
      <%= f.label :target_company_size, "Company size" %><%= f.select :target_company_size, ['Self-employed', '1-10 employees', '11-50 employees', '51-200 employees', '201-500 employees', '501-1,000 employees', '1,001-5,000 employees', '5,001-10,000 employees', 'More than 10,000 employees'] %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_industry, "Industry" %><%= f.select :target_industry, ['Art & Entertainment', 'Autos & Vehicles', 'Beauty & Fitness', 'Books & Litterature', 'Business & Industrial', 'Computer & Electronics', 'Finance', 'Food & Drinks', 'Games', 'Hobbies & Leisure', 'Home & Garden', 'Internet & Telecom', 'Jobs & Education', 'Law & Government', 'News', 'Online Communities', 'People & Society', 'Pets & Animals', 'Real Estate', 'Science', 'Shopping', 'Sports', 'Travel']  %>
    </div>

  </div>

然而,我似乎无法做到这一点:当我访问Calendars#New视图中,我确实看到了选择 B2C 或 B2B 的单选按钮,但无论我选择哪个按钮,下面都不会显示任何内容(B2C 部分和 B2B 部分都没有)。

我缺少什么?

—————

UPDATE 2:所以,我更新了我的代码作为Ziv Galili的新评论,即:注意按钮组的名称,它实际上是calendar[target_relationship].

当我这样做并尝试进入我的视图时,我得到了一个execJS::RuntimeError,这让我意识到我们使用的是纯 JavaScript,而我的 Rails 应用程序似乎使用的是 CoffeeScript。

所以,我删除了app/assets/javascript/custom/calendars.js,将 Ziv Galili 的代码转换为 CoffeeScript 并将其添加到 app/assets/javascript/calendars.coffee 中:

$('input[type=radio][name=calendar[target_relationship]]').change ->
  # first: hide all the divs
  $('#calendar_details_b2c').css 'display', 'none'
  $('#calendar_details_b2b').css 'display', 'none'
  # then get the div ID to show (i stored it in the "value" of the radio button
  fieldToShow = $(this).val()
  # now use jQuery selector and change the display setting of that field
  $('#' + fieldToShow).css 'display', 'block'
  return

我也更换了//= require_tree ./custom with //= require_tree .以确保我所有的.coffee文件是通过加载的application.js.

尽管更新了所有这些代码,我仍然没有得到我期望的结果:没有一个divs 显示在我的视图中:

enter image description here

我一定错过了一些非常非常明显的东西,但我不知道它是什么。

任何想法?

—————

任何形式的帮助将不胜感激。


我会做这样的事情:

jsFiddle

解释:

假设 HTML 为:

<form action="">
  <input type="radio" name="calendars" value="calendar_details_b2b">B2B
  <br>
  <input type="radio" name="calendars" value="calendar_details_b2c">B2C
</form>
<div id="calendar_details_b2c" style=>
  content of B2C
</div>
<div id="calendar_details_b2b">
  content of B2B
</div>

添加 css 代码,这样 div 就不会在页面加载时显示:

#calendar_details_b2c,
#calendar_details_b2b
{
  display: none;
}

JS 代码将是:

$('input[type=radio][name=calendars]').change(function () {
  // first: hide all the divs
  $('#calendar_details_b2c').css("display","none");
  $('#calendar_details_b2b').css("display","none");

  // then get the div ID to show (i stored it in the "value" of the radio button
  var fieldToShow = $(this).val();
  // now use jQuery selector and change the display setting of that field
  $("#" + fieldToShow).css("display","block");
});

UPDATE:

至于您的更新,请注意 JS 部分中按钮组的名称与 HTML 文件中的名称相匹配:

js:

$('input[type=radio][name=NAME_OF_BUTTON_GROUP]')

要在 HTML 中查找名称,您可以(在 chrome 中):

  1. 右键单击其中一个单选按钮
  2. 按检查元素
  3. 在元素检查器中查找输入的 name 属性

<input checked="checked" id="something_calendar_details_b2c" name="这就是名字" type="radio" value="calendar_details_b2c">

注意:如果名称中有方括号(或任何其他特殊字符),则应该用撇号将其括起来

$('input[type=radio][name="calendar[target_relationship]"]')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 4 表单:基于单选按钮选择条件显示字段 的相关文章

  • 指定 HTML5 输入类型 = 日期的值输出?

    我想将本机日期选择器添加到我的应用程序中 该应用程序当前使用遗留的本地系统 日期输入支持尚未广泛普及 但如果我可以基于兼容性提供这两种实现 那就太理想了 有没有办法指定 HTML 日期选择器给出的值的输出 歌剧的默认设置是yyyy mm d
  • 处理rails应用程序中的rack_throttle异常

    当超出速率限制时 如何处理由rack throttle gem 生成的错误 现在我只收到包含以下内容的回复 Internal Server Error undefined method each for 403 Forbidden Rate
  • 替换img路径jquery

    我正在尝试替换 jquery 中的 img 路径 注入远程页面 replaceexample com thumbs withexample com images 我已经尝试过这个 但似乎不起作用 img attr src replace t
  • 为什么Promise中的代码会同步执行? [复制]

    这个问题在这里已经有答案了 在我的项目中 我有一个很长时间运行的操作 所以我决定将其放入Promise因为我认为这样我就可以在里面的代码继续执行其他操作Promise正在跑步 调试的时候发现外面的代码Promise仅当里面的代码执行Prom
  • document.write 在同一页面上显示内容。

    我对 javascript document write 方法有疑问 大多数情况下 当我使用 document write 时 它会向我显示在不同页面中使用该方法编写的内容 例如 如果我写这样的命令 document write Hello
  • 在给定索引上将字符串分成两部分并返回两部分

    我有一个字符串 需要在给定索引上拆分 然后返回两个部分 并用逗号分隔 例如 string 8211 8 211 98700 98 700 因此 我需要能够在任何给定索引上拆分字符串 然后返回字符串的两半 内置方法似乎执行分割 但只返回分割的
  • 如何跨多个 React Redux 组件使用 requestAnimationFrame 实现游戏循环?

    努力思考最好的解决办法 我可以使用递归调用requestAnimationFrame有一个游戏循环 export interface Props name string points number onIncrement gt void o
  • 基于范围内变量的角度设置形式动作

    我一直在尝试设置一个搜索表单 可以在其中注入表单操作属性 在我的表格中我有
  • 使用 eval 时不会受到 XSS 威胁

    我正在制作 不是现在 但我仍然对这个感到好奇 一款使用 HTML5 和 JS 的游戏 我想要的是人们可以插入自定义脚本 但要安全 function executeCustomJS code eval code bad 当然这段代码非常糟糕
  • iPhone 上的锁定方向 UIWebView

    有没有办法锁定 UIWebView 的方向 使用 Obj C JS 还是 Html 我不想有按钮或任何东西 我只想在应用程序打开时将其锁定为纵向 好像这个堆栈溢出帖子 https stackoverflow com questions 43
  • 无法从 JQuery ajax 调用接收 JSON

    我已经确定来自服务器的 JSON 是有效的 手动进行 ajax 调用 但我真的很想使用 JQuery 我还使用 firebug 确定发送到服务器的 post URL 是正确的 但是 错误回调仍然被触发 解析错误 我还尝试了数据类型 文本 我
  • 如何让php页面从html页面接收ajax post

    我有一个非常简单的表单 其中有一个名字输入字段 我捕获了表单数据 并使用标准 jQuery 发布方法通过 ajax 将其传输到 PHP 页面 但是 我根本无法从 PHP 页面获得任何在服务器端捕获数据的响应 我不确定我做错了什么或缺少什么
  • 使用 jQuery 从 ASP.Net JSON 服务获取数据

    我正在尝试调用 Google 地图地理编码 API 从纬度 经度对中获取格式化的地址 然后将其记录到控制台 我正在尝试获取为给定位置返回的第一个 formatted address 项目 我很简单无法从 JSON 中提取该项目 我不知道为什
  • WebpackError:ReferenceError:Gatsby 上未定义窗口

    我已经在互联网上进行了大量搜索 但无法解决这个问题 我正在使用 Gasby 开发静态页面 但遇到此错误 WebpackError ReferenceError window is not defined 我的线索是 这与我正在使用的引导 模
  • Unicorn + Rails + 大型上传

    我试图在使用 Rails 在 Heroku 上运行 Unicorn 时允许进行大型上传 但我意识到任何大型上传可能需要比 Unicorn 工作线程的超时时间更长的时间 这意味着 我见过这种情况发生 Unicorn 主进程将杀死上传大文件的工
  • 如何计算一行中Flexbox项目的数量?

    网格是使用 CSS flexbox 实现的 Example http jsbin com jumosicasi edit html css js output 本示例中的行数为 4 因为我出于演示目的固定了容器宽度 但是 实际上 它可以根据
  • 加载 Angular 库时,IE9 和 IE10 中出现 Angular JS“SCRIPT5007:预期对象”错误

    我正在开发一个 AngularJS 应用程序 该应用程序应在 Firefox IE 9 和 IE 10 上运行 我使用最新版本的 angularjs 库 现在是 1 3 15 服务器端是在JavaEE平台上用Java编写的 服务器运行在Gl
  • 从json中获取所有子节点

    我有以下 json var source k 01 k 02 children k 05 k 06 children k ABC k PQR k 07 k 03 我希望能够指定 k 的值并取回所有孩子 以及孙
  • Radiobutton-带有纯 html/css 的按钮

    是否可以创建像这样的单选按钮JQuery http jqueryui com demos button radio那些 用纯html css thanks 试试这个小提琴 http jsfiddle net mcXm7 1 http jsf
  • 在引导程序中以编程方式更改选项卡窗格选项卡

    我使用的选项卡窗格定义为 ul class nav nav tabs li a href personal Personal Information a li li class active a href contact Contact a

随机推荐

  • 如何将 Eigen::Matrix 映射到 std::vector

    例如 如果我有一个Eigen MatrixXd大小为 10 列和 3 行 我如何将其别名为std vector的 10 个元素Eigen Vector3d 当我说别名时 我的意思是使用相同的内存块而不进行复制 我知道我可以通过以下方式进行反
  • 如何使用 Firebase 云消息传递

    我找不到任何有关新版本的文档 版本7和版本6有大量文档 而版本9几乎不存在 不仅是我 大多数人都找不到 我只是想向后台发送简单的通知 如果有人分享有关新版本的文档 我将非常高兴 或者我应该使用旧版本 我想您知道如何将 firebase 添加
  • 在 C# 中将字符串转换为枚举标记[重复]

    这个问题在这里已经有答案了 可能的重复 如何在 C 中将字符串转换为枚举 如何在 C 中将字符串 文本 转换 强制转换 为 Enum 标记值 你可以这样做 MyEnum oMyEnum MyEnum Enum Parse typeof My
  • 使用 VBA 获取在 VBA 中使用的唯一值?

    我目前会使用类似的东西与范围 单元格或类似的许多不同的方式相同的基本原理 Range A1 Range A1 End xlDown AdvancedFilter Action xlFilterCopy CopyToRange Range I
  • 尝试为 Haskell 中的函数创建有效的算法

    我正在寻找一种有效的多项式时间解决方案来解决以下问题 实现一个递归函数节点 x y 来计算数字三角形中的第 x y 个数字 定义为 g x y 0 if x gt y 1 if x y 0 0 sum of all incoming pat
  • 使用 VS 2015 Update 2 配置 tslint

    我无法让 tslint 在 Visual Studio 2015 中正常工作 我应该明确指出 我安装了更新 2 我有 Web Essentials 但它声称它不再包含 linters 我没有网络分析器 如果这很重要的话 这是一个 ASP N
  • 有没有办法在 Gradle KTS 中实例化 KTS 脚本引擎?

    我想在我的项目构建过程中使用 3d party 库 库方法需要 ScriptEngine 当我尝试实例化它时 出现错误 java lang IllegalArgumentException Unable to construct scrip
  • Mongoose findOneAndUpdate:更新对象数组中的对象

    我有与此线程中描述的完全相同的问题 因此有类似的标题 Mongoose findOneAndUpdate 更新对象数组中的对象 给定这个模型 const SavedFoodsSchema new Schema user type Schem
  • 为什么我的组件没有包装在 Swing 的 FlowLayout 中?

    为什么我的组件没有使用 FlowLayout 包装在这个 JPanel 中 它们只是跑出屏幕并且仅部分可见 JPanel panel new JPanel new FlowLayout panel add new JLabel TEST r
  • 如何在nodejs中使用typescript/flow而不编译它

    有人可以给我一些建议或链接来讨论我是否应该为后端捆绑 JS 我尝试用这个标题 和类似的词 搜索谷歌 但找不到任何有用的链接 只是想知道 假设我正在使用最新的 Node JS es6 ready 我应该捆绑 编译 JS 吗 如果没有 我该如何
  • 循环 Observable 数据,推送到数组,并显示数组打字稿的所有结果

    我如何循环遍历我作为 Observable 订阅的数据 将其推送到数组 并显示数组的全部数据 我目前的代码仅显示每个 页面 的数据 而不是所有页面 我之所以要这样做 是因为我想制作无限滚动 谢谢你 成分 this storiesServic
  • 来自资源字符串的 Toast.makeText

    我有一个名为 MyPrimaryClass 的类 该类有一个按钮 按下时会创建一个类为 myClassForResult 的 Intent 我用它来启动它 startActivityForResult myIntentOfMyClassFo
  • Python:如果 DataFrame 之间的其他值匹配,则对 DataFrame 中的值求和

    我有两个不同长度的数据帧 如下所示 数据框A FirstName LastName Adam Smith John Johnson 数据框B First Last Value Adam Smith 1 2 Adam Smith 1 5 Ad
  • 从实体框架实体获取列数据类型

    使用实体框架 5 首先使用数据库 是否可以 在运行时 获取实体属性所代表的数据库列的数据类型 如果更容易的话 net 类型也可以正常工作 IEnumerable
  • android渲染使用CPU而不是GPU?

    很奇怪的是 在 systrace 工具中 当我看到 SurfaceFlinger 执行绘图命令和窗口合成时 它是在 CPU 上运行的 而不是在 GPU 上运行的 但根据 Romain Guy 的 google 演讲 他们表示绘图命令的组合和
  • PHP 致命错误:使用 laravel4 找不到类“PDO”

    一小时后尝试解决这个问题我失败了 我的错误消息是 Generating autoload files PHP Fatal error Class PDO not found in usr share nginx html laravel a
  • C 函数局部变量的作用域

    当我开始用 C 语言编程时 我就听说过以下场景 尝试从外部访问函数局部变量将导致错误 或垃圾值 由于当我们从函数返回时堆栈被清除 但我的下面的代码示例打印的值为 50 我正在使用最新的 GCC 编译器编译代码 include
  • 如何根据下面的示例从 SQL Server 检索数据?

    实际上我在这里发布了与此相关的类似问题如何按照下面的要求从 SQL Server 检索数据 现在我需要对此进行一些更改 因此请在提出建议之前查看此内容 我有一张这样的桌子 CustName Country RecordedTime Alex
  • 使用 Scala 符号文字会导致 NoSuchMethod

    我最近开始使用 Scala 我在其中编写了一个 DSL 可用于描述中的处理管道medici 在我的 DSL 中 我使用符号来表示锚点 它可用于在管道中放置叉子 或 T 恤 如果您愿意 这是一个正确运行的小示例程序 object Test e
  • Rails 4 表单:基于单选按钮选择条件显示字段

    首先 如果这个问题很愚蠢 请原谅我 我刚刚开始了解 Rails Javascript 和 jQuery 对我来说是一个全新的世界 我发现了以下类似的问题 但根本不明白它们如何适用于我的情况 如果选中复选框则显示 隐藏 div 根据所选的单选