james
james

Reputation: 4049

document.ready not firing?

This is NOT a case of not having jQuery loaded, but I do feel like I'm missing something else that's simple... On this staging site: https://hidden-tundra-8656.herokuapp.com/orders, once the page finishes loading, the "Camping & backpacking" should be auto-selected.

This is the code:

$(document).ready( function() {
  console.log("about to trigger initial click")
  $(".category-selector[data-id='"+gon.category_to_start+"']").click()
}) 

It's definitely not happening. Any thoughts? The only thing that I can think of is that the category-selectors are interpolated from Ruby, see view code below, so maybe that's causing it?

<div class="row">
   <% @item_categories.each do |ic| %>
      <div class="col-xs-6 category-box">
          <div class="row category-row">
              <div class="col-xs-12 table-display category-selector text-center" data-id="<%=ic.id%>">
                  <span class="labeler-response table-cell-display">
                     <%= ic.name %>
                  </span>
              </div>
          </div>
      </div>
  <% end %>
</div>

A little bit more info.

The console.log in the code is not triggered, and gon.category_to_start is defined. ALL of the other jquery on the page is working perfectly.

On this page, it is loading the application.js and a separate orders/new.js that contains the code in question. It loads jquery first, then application.js then new.js. For argument's sake, I just tried to load the code snippet into application.js and it didn't work there either. This works fine in local server.

Upvotes: 0

Views: 978

Answers (4)

siegy22
siegy22

Reputation: 4413

If you're using Turbolinks (default if you setup a rails project), you should use page:load as an event.

$(document).on("page:load", function() {
  console.log("about to trigger initial click");
  $(".category-selector[data-id='"+gon.category_to_start+"']").click();
});

NOTE:

If you're in production mode, please make sure that you run bin/rake assets:precompile to keep your assets up-to-date.

Upvotes: 1

james
james

Reputation: 4049

facepalm answer: precompile assets

Upvotes: 0

warkitty
warkitty

Reputation: 116

Why include the data-id in the selector? You can $('.classname').trigger.('click') on document ready

Upvotes: 0

brk
brk

Reputation: 50316

The issue seems to be with this line

$(".category-selector[data-id='"+gon.category_to_start+"']").click()

There is no reference to gon.category_to_start so probably data-id is getting some undefined value.

Also you can check if the console.log is logging any value

"Camping & backpacking" should be auto-selected.

But I am seeing category-selector is on a div element. Do you mena to select the div, since auto-selection works on checkbox or radio button

Upvotes: 0

Related Questions