lundi 17 décembre 2018

Rails: javascript addEventListener does not find element in dynamic form

I am trying to implement a dynamic form in a Rails App through AJAX and did a couple of tutorials, but without success.

The Javascript part from my application js file in the asset folder

var land = document.getElementById("cart_land_id");
land.addEventListener("change", function(){
  Rails.ajax({
    url: "/carts?land=" + land.value,
    type: "GET"
  })
})

For this form in a view:

<%= form_for @cart, :url => {:action => "show_shipping"}, :html => {:method => "get"} do |f| %>
  <%= f.select :land_id, options_for_select(@lands.map { |l| [l.name.titleize, l.id] }, {:id => 'lands_select', :prompt => "select a country"}) %><br>
  <%= f.select :shippingservice_id, options_for_select([]) %><br>
  <%= f.submit "Calculate shipping" %>
<% end %>

Which gets rendered as:

<form accept-charset="UTF-8" action="/carts/show_shipping/4" class="edit_cart" id="edit_cart_4" method="get">
  <div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div>
  <select id="cart_land_id" name="cart[land_id]"><option value="1">Afghanistan</option>
  ...
  <select id="cart_shippingservice_id" name="cart[shippingservice_id]"></select><br>
  <input name="commit" type="submit" value="Calculate shipping" />
</form>

produces an

TypeError: null is not an object (evaluating 'land.addEventListener')         

I have jQuery in my Javascript directory.

Why does this happen and how can I solve this?

Aucun commentaire:

Enregistrer un commentaire