anndrew78
anndrew78

Reputation: 196

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!

Upvotes: 0

Views: 35

Answers (1)

max
max

Reputation: 101831

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.

Upvotes: 1

Related Questions