简体   繁体   中英

Javascript into Coffee

I struggle with some javascript code in rails. I use this code to make two drop down menus dynamically. I need to "translate" the code into js.coffee, but I have no clue how to do that.

This is my javascript code:

    <script>
$(document).ready(function() {
        $('#categories_select').change(function() {
          $.ajax({
            url: "<%= update_subcategories_path %>",
            data: {
              category_id : $('#categories_select').val()
            },
            dataType: "script"
          });
        });
      });
</script>

I tried it with this one, but it does not work:

$ ->
  $(document).on 'change', '#categories_select', (evt) ->
    $.ajax 'update_subcategories',
      type: 'GET'
      dataType: 'script'
      data: {
        country_id: $("#categories_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic category select OK!")

And this is my form:

    <%= form_for(@search) do |f| %>
<%= f.collection_select :category_id,  @categories,  :id, :name, {:prompt   => "Select category"}, {:id => 'categories_select'} %>
<%= f.collection_select :subcategory_id, @subcategories, :id, :name, {:prompt   => "Select subcategory"}, {:id => 'subcategories_select'} %>  

With the script it's working fine but I would like to get this javascript out of my html file. Can anyone help me with this?

Thank you for any help!

For what it's worth, I think it looks as if you have tried to convert your code to CoffeeScript and change it at the same time. You should probably do the first one first, check that it works, and then the second one.

This compiles for me, and to the same javascript as yours above. Does it work for you? If so, move on from there:

$(document).ready ->
  $('#categories_select').change ->
      $.ajax
        url: "<%= update_subcategories_path %>",
        data: 
          category_id : $('#categories_select').val()
        dataType: "script"

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