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

时间:2015-10-16 22:47:25

标签: javascript jquery ruby-on-rails forms ruby-on-rails-4

首先,请原谅我这个问题是否愚蠢,我只是开始围绕Rails和Javascript& jQuery对我来说是一个全新的世界。

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

话虽如此,这是我的问题。

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

<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>

根据用户检查第一个单选按钮(&#34; B2C&#34;或&#34; B2B&#34;),我想显示calendar_details_b2c {{1} },或div calendar_details_b2b

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

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

- - - -

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

application.js

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"); }); }); 中,我添加了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> 视图时,我确实看到单选按钮选择B2C或B2B,但无论选择哪个按钮,都不会显示任何内容下面(B2C部分和B2B部分都没有。)

我错过了什么?

- - - -

更新2 :所以,我将我的代码更新为Ziv Galili的新评论,即:注意按钮组的名称,实际上是Calendars#New

当我这样做,并试图进入我的观点时,我得到了一个calendar[target_relationship],这让我意识到我们使用的是纯JavaScript,而我的Rails应用程序似乎正在使用CoffeeScript。

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

app/assets/javascript/custom/calendars.js

我还将$('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,以确保通过//= require_tree .加载了所有.coffee个文件。

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

enter image description here

我必须遗漏一些非常非常明显的东西,但我无法弄清楚它是什么。

有什么想法吗?

- - - -

任何形式的帮助都将受到高度赞赏。

3 个答案:

答案 0 :(得分:4)

我会做这样的事情:

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");
});

<强>更新

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

JS:

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

在HTML中找到您可以使用的名称(在chrome中):

  1. 右键单击其中一个单选按钮
  2. 按Inspect Element
  3. 在元素检查器中查找输入的名称属性
  4. <input checked="checked" id="something_calendar_details_b2c" name=" 这就是姓名 " type="radio" value="calendar_details_b2c">

    注意:如果名称(或任何其他特殊字符)中有方括号,则应使用撇号包装它

    $('input[type=radio][name="calendar[target_relationship]"]')
    

答案 1 :(得分:1)

您可以在js文件中轻松使用jQuery函数。

只需使用

$('input[type=radio][name=abc]').change(function() {
    // check radio button value by this.value
    // hide div blocks by $('div#id').hide();
});

答案 2 :(得分:-1)

&#13;
&#13;
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script>

	$(function() {
          		var $divs = $('#divs > div');
          		$divs.first().show();
          		$('input[type=radio]').on('change',function() {
                	$divs.hide();
                	$divs.eq( $('input[type=radio]').index( this ) ).show();
           		});
			});
	
</script>
&#13;
  #divs div {
      display:none;
  }
&#13;
<div class="container">
	<div class="form-container">
		<form class="registerform" action="register.php" method="post" id="registerform">
			<h3 class="title">Register</h3>
			<div class="cdiv">User Name:</div>
			<div class="cdiv"><input class="ipcontact" name="username" type="text" id="username"></div>
			<div class="cdiv">Password:</div>
			<div class="cdiv"><input class="ipcontact" name="password" type="password" id="password"></div>
			<div class="cdiv">Name:</div>
			<div class="cdiv"><input class="ipcontact" name="name" type="text" id="name"></div>
			<div class="cdiv">E-mail:</div>
			<div class="cdiv"><input class="ipcontact" name="email" type="email" id="email"></div>
			<div class="cdiv">Phone Number:</div>
			<div class="cdiv"><input class="ipcontact" name="phonenumber" type="number" id="phonenumber"></div>
			<div class="cdiv">Student<input type="radio" name="check" checked value="1">Teacher<input type="radio" name="check" value="2"></div>


			<div id = "divs">
				<div class="form-group" id = "div2">
					Student Class:<br/>
					<input class="ipcontact" name="studentclass" type="text" id="studentclass"><br/>
					Student Roll Number:<br/>
					<input class="ipcontact" name="studentrollnumber" type="text" id="studentrollnumber"> 
				</div>
				<div class="form-group" id = "div1" >
					Teacher type:<br/>
					<input class="ipcontact" name="teachertype" type="text" id="teachertype">
				</div>
			</div>
			<div class="form-group"> <input class="login-button" type="submit" name="submit" value="Register"></div>
		</form>
	</div>
</div>
&#13;
&#13;
&#13;

<!DOCTYPE html>
<html>

<head>
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js">                                    </script>
</head>

<body>
<script>


$(function() {
            var $divs = $('#divs > div');
            $divs.first().show();
            $('input[type=radio]').on('change',function() {
                $divs.hide();
                $divs.eq( $('input[type=radio]').index( this ) ).show();
            });
        });

</script>

<div class="container">
<div class="form-container">
    <form class="registerform" action="register.php" method="post" id="registerform">
        <h3 class="title">Register</h3>
        <div class="cdiv">User Name:</div>
        <div class="cdiv"><input class="ipcontact" name="username" type="text" id="username"></div>
        <div class="cdiv">Password:</div>
        <div class="cdiv"><input class="ipcontact" name="password" type="password" id="password"></div>
        <div class="cdiv">Name:</div>
        <div class="cdiv"><input class="ipcontact" name="name" type="text" id="name"></div>
        <div class="cdiv">E-mail:</div>
        <div class="cdiv"><input class="ipcontact" name="email" type="email" id="email"></div>
        <div class="cdiv">Phone Number:</div>
        <div class="cdiv"><input class="ipcontact" name="phonenumber" type="number" id="phonenumber"></div>
        <div class="cdiv">Student<input type="radio" name="check" checked value="1">Teacher<input type="radio" name="check" value="2"></div>


        <div id = "divs">
            <div class="form-group" id = "div2">
                Student Class:<br/>
                <input class="ipcontact" name="studentclass" type="text" id="studentclass"><br/>
                Student Roll Number:<br/>
                <input class="ipcontact" name="studentrollnumber" type="text" id="studentrollnumber"> 
            </div>
            <div class="form-group" id = "div1" >
                Teacher type:<br/>
                <input class="ipcontact" name="teachertype" type="text" id="teachertype">
            </div>
        </div>
        <div class="form-group"> <input class="login-button" type="submit" name="submit" value="Register"></div>
    </form>
</div>
</div>

</body>
</html>