简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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