Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

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.

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

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

If I click on id=”metrical” I want to see text “METRICAL” in <div id=”cargo_form”></div>.

So I put in my new.js.erb next jquery code:

$('#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>

What I am doing wrong? Thanks for help!

question from:https://stackoverflow.com/questions/65910406/how-to-use-jquery-click-method-with-form-select-in-ruby-on-rails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to put the code in your webpack application.js or in the assets pipeline.

$(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. 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.

SSC is not needed at all when you're just adding a simple event handler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...