简体   繁体   English

Rails形式:当在另一个字段中选择特定选项时,如何模糊一个字段

[英]rails forms:how do i blur a field when a particular option is selected in another field

This is gonna be my first attempt at javascript. 这将是我第一次尝试使用javascript。 When someone selects a particular option in a select list, I want another field in the form to go dull because it's no longer applicable. 当某人在选择列表中选择一个特定选项时,我希望表单中的另一个字段变暗,因为它不再适用。 I guess I have to write an onchange event handler and have it execute a javascript script that detects the selected option and renders a form with the relevant field dull if the option's selected or renders a different form if a different option was selected ... anyone can give me a start please ~ thanks 我想我必须编写一个onchange事件处理程序,并让它执行一个JavaScript脚本,该脚本检测选定的选项,如果选择了该选项,则呈现带有相关字段变暗的表单;如果选择了另一个选项,则呈现不同的表单...任何人可以给我一个开始〜谢谢

You may try something like this: 您可以尝试如下操作:

$(document).on('blur', "selector", function (e) { 
  // do what you want to do, change background, color, etc...
});

Instead of selector type in the class, id, or other selector for the element you need to change. 您无需更改元素的类,id或其他选择器中的selector类型。

You can add this snippet to any javascript file included in app/assets/javascripts/application.js . 您可以将此代码段添加到app/assets/javascripts/application.js包含的任何javascript文件中。 You can create a new one and add it there if none existing suits you... 您可以创建一个新的文件,然后在现有文件不适合您的情况下添加它

If application.js ends with //= require_tree . 如果application.js//= require_tree .结尾//= require_tree . it means that it will require all files in that directory and you do not need to manually require them. 这意味着它将需要该目录中的所有文件,而您无需手动要求它们。

Btw, concerning the terminology, element has focus when it is clicked on. 顺便说一句,关于术语,单击元素会使其具有焦点。 When element looses focus (for example some other element is clicked, or tab is pressed), it gets blured. 当元素失去焦点时(例如,单击某些其他元素或按下选项卡),它会变得模糊。 That is when on('blur') gets called. 那是当on('blur')被调用时。

This is how you can write on('change') for a select: 这是您可以在select上写on('change')的方法:

$(document).on('change', 'select', function (e) {
  // do something
});

Instead of 'select' you need to type in the correct selector, otherwise it will get triggered each time any select changes. 您需要输入正确的选择器,而不是“选择”,否则每次选择更改时都会触发该选择器。

I need the action to be triggered only when i specific value in the select list is selected 我仅在选择列表中的特定值时才需要触发操作

No problem, try this: 没问题,试试这个:

$(document).on('change', 'select', function (e) {
  if ($(this).val() == 'specific_value'){
    // do something
  }
});

UPDATE 更新

I wanna make the call to jquery from my view and replace the element in the view with the output of the jquery filename.js.erb file 我想从我的视图中调用jquery,并用jquery filename.js.erb文件的输出替换视图中的元素

jQuery, and all other javascript is being executed within the client (the web browser), and your file filename.js.erb is located on the server, and it needs to be processed by rails. jQuery和所有其他JavaScript正在客户端(Web浏览器)中执行,并且文件filename.js.erb位于服务器上,并且需要用rails处理。

This is how it can be done: 这是可以做到的:

  1. ajax request is sent to the server ajax请求发送到服务器
  2. it gets picked up by rails, and it is routed to a controller 它被导轨拾取,并被路由到控制器
  3. it is processed by a controller action 它由控制器动作处理
  4. a javascript view is rendered and posted as a response 呈现javascript视图并作为响应发布

There are two ways to achieve this. 有两种方法可以实现此目的。 First I will explain the steps that are common for both approaches. 首先,我将解释两种方法共有的步骤。

You will need to add a new route to your routes.rb that you will use as an endpoint for your ajax call. 您将需要在routes.rb中添加新路由, routes.rb其用作ajax调用的端点。 Here you can read more about adding routes to rails, but for the purpose of this answer, I will use this simple route (with a dumb name, you should change that for sure): 在这里,您可以阅读有关将路线添加到rails的更多信息,但是出于此答案的目的,我将使用以下简单路线(使用愚蠢的名称,请务必更改此名称):

resource :my_ajax, only: :create

And this is what the route looks like: 这是路线的样子:

rake routes|grep my_ajax
# my_ajax POST    /my_ajax(.:format)   my_ajaxes#create

It expects that you have MyAjaxesController , and within it create action. 它期望您拥有MyAjaxesController ,并在其中create动作。 You should also make your controller able to respond to javascript requests by adding this to the controller: 您还应该通过将其添加到控制器中,使控制器能够响应javascript请求:

class MyAjaxesController < AdminController
  # ...
  respond_to :js
  # ...

  def create
    # ...
  end
end

You also need to have a view for that action: create.js.erb . 您还需要查看该操作的视图: create.js.erb You can add javascript to that view, but there you can also make use of everything rails controller makes available for you. 您可以将javascript添加到该视图,但是在这里您还可以利用rails控制器为您提供的所有功能。 So, you can use any instance variables or you can render partials. 因此,您可以使用任何实例变量,也可以呈现局部变量。

This is how a partial can be rendered: 这是局部渲染的方式:

$('#element').html('<%= j(render partial: "_my_partial", locals: { my_var: @my_var }) %>');

When the response to ajax request is received by the browser, it just replaces the contents of #element with whatever html got rendered by that partial. 当浏览器收到对ajax请求的响应时,它只是用该部分呈现的html替换#element的内容。

Ok, coming now to the differences to the approaches. 好的,现在来看方法的差异。

You could send an ajax request (by jQuery) aiming to the endpoint that you created (mind the method, the route I created expects POST). 您可以发送ajax请求(通过jQuery),该请求针对您创建的端点(注意方法,我创建的路由需要POST)。 In that case you need to manually manage any response you receive. 在这种情况下,您需要手动管理收到的任何回复。

However, there is a rails way of doing it. 但是,有一种方法可以做到。 You could create a form with all of its fields hidden (you don't need it in the view, you just need it as a means to send a request). 您可以创建一个隐藏所有字段的表单(视图中不需要它,只需要它作为发送请求的一种方式)。 You need to specify the action for the form, the method, and also set remote: true , to make sure that it is submitted asynchronously. 您需要为表单,方法指定操作,还需要设置remote: true ,以确保它是异步提交的。

Here's an example: 这是一个例子:

<%= form_tag(my_ajax_path, remote: true, method: :post) do %>
  <%= hidden_field_tag :some_field %>
<% end %>

All you need to do is submit this form whenever you want (for example by looking it up with an id and calling submit: $('#my_form').submit(); and it will do the rest. You can also dynamically change any hidden inputs of the form prior to submitting. 您需要做的就是随时随地提交此表单(例如,通过查找ID并调用$('#my_form').submit();$('#my_form').submit();剩下的事情就会完成。您还可以动态更改提交之前表单的任何隐藏输入。

$(document).on('change', 'select', function (e) {
  if ($(this).val() == 'specific_value'){
    $('#my_form').submit();
  }
});

As for the testing the controller action by rspec, in order for it to work, do not forget that what controller expects and renders is javascript requests, so you need to specify the format: 至于通过rspec测试控制器动作,为了使其正常工作,请不要忘记控制器期望并呈现的是javascript请求,因此您需要指定格式:

it 'my test' do
  # expectations
  response = post :my_ajax, format: :js
  # assertions
end

You can do this by using change event of jquery. 您可以通过使用jquery的change事件来执行此操作。 For example your option select like this: 例如,您的选项选择如下:

<%= f.select :state, [['NSW'], ['VIC'], ['SA'], ['WA'], ['QLD']] %>

Then, you have to create jquery event to do your next action. 然后,您必须创建jquery事件以执行下一步操作。 For example: 例如:

<script>
  $(document).ready(function(){ 
   // hidding form
   $("#form_1").hide();
   $("#form_2").hide();
   // showing form after user changes the select option
    $("#user_state").change(function(){
      var selected = $(this).val();
      if(selected == "VIC") {
        $("#form_1").show();
      } else {
        $("#form_2").show();
      }
    });
  });
</script>

I hope this help you to attempt the first experience for trying jquery. 我希望这可以帮助您尝试尝试jquery的初体验。 Good luck! 祝好运!

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

相关问题 如何创建一个下拉列表,当选中该下拉列表时会更新一个输入字段? - How do I create a dropdown that when selected updates an input field? 从第一个选择一个选项时,如何取消隐藏另一个选择字段? - How to unhide another select field when one option is selected from the first? 表单字段:如何更改模糊背景? - Form Field: How do I change the background on blur? 选择某个选项后,如何将值传递给隐藏的表单字段? - How do you pass a value to a hidden form field when a certain option is selected? 如果在输入字段上按下转义键,而不是对该输入字段的模糊事件执行某些操作,该怎么办? - How do you do something when the escape key is pressed on an input field, but not on blur events for that input field? Gravity Forms - 如何根据在另一个下拉字段中选择的值隐藏下拉定价字段中的某些选项 - Gravity Forms - How to Hide Some Options in a Dropdown pricing Field based on Value selected in Another Dropdown field 当另一个字段的值为0时,如何禁用复选框? - How do I disable a checkbox when the value in another field is 0? 发生模糊时如何限制对字段的验证? - How to limit validation on a field when blur fires? 选择下拉列表字段选项时显示文本框 - Show textbox when dropdownlist field option is selected 选择选项时更改必填字段形式 - Change required field form when option is selected
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM