简体   繁体   English

如何在 Rails 上的 Ruby 中将 jquery.click() 方法与 form.select 一起使用?

[英]How to use jquery .click() method with form.select in Ruby on Rails?

I have a form with selection input called units_system that can be metrical or imperial.我有一个带有选择输入的表单,称为 units_system,可以是公制或英制。

<%= form.select :units_system, [['metrical', id: 'metrical'], ['imperial', id: :imperial]], {prompt: 'Select units system'}, {class: "form-control", id: :item_units_system}%>

It is generate html生成 html

<select class="form-control" id="lot_units_system" name="lot[units_system]"><option value="">Select units system</option>
<option id="metrical" value="metrical">metrical</option>
<option id="imperial" value="imperial">imperial</option></select>

Depend of my choose I would like render different partials in <div id=”cargo_form”></div>取决于我的选择,我想在<div id=”cargo_form”></div>中渲染不同的部分

If I click on id=”metrical” I want to see text “METRICAL” in <div id=”cargo_form”></div> .如果我点击 id=”metrical” 我想在<div id=”cargo_form”></div>中看到文本“METRICAL”。

So I put in my new.js.erb next jquery code:所以我在我的 new.js.erb 下一个 jquery 代码:

$('#metrical').click(function(e) {
    e.preventDefault();
    $('#cargo_form').html('METRICAL');
});

But nothing gonna heppened.但什么都不会发生。 I don't see any result in <div id=”cargo_form”></div>我在<div id=”cargo_form”></div>不到任何结果

What I am doing wrong?我做错了什么? Thanks for help!感谢帮助!

You want to put the code in your webpack application.js or in the assets pipeline.您想将代码放入 webpack application.js或资产管道中。

$(document).on('click', '#metrical', function(e) {
  e.preventDefault();
  $('#cargo_form').html('METRICAL');
});

Server Side concerns - which is basically the combination of Rails UJS sending XHR requests for JS and rendering a js.erb view is used to basically just replace contents in the page with strings generated on the server side.服务器端问题 - 这基本上是 Rails UJS 为 JS 发送 XHR 请求和呈现js.erb视图的组合,基本上只是用服务器端生成的字符串替换页面中的内容。 This lets you reuse server side templates on the frontend.这使您可以在前端重用服务器端模板。

They usually look like this:它们通常看起来像这样:

document.querySelector('#someElement')
        .innerHTML = "<%= j(render 'something') %>";

This really just replaces contents on the page when Rails UJS pops the javascript response into a script tag.当 Rails UJS 将 javascript 响应弹出到脚本标记中时,这实际上只是替换了页面上的内容。

SSC is not needed at all when you're just adding a simple event handler.当您只是添加一个简单的事件处理程序时,根本不需要 SSC。

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

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