Eric Baldwin
Eric Baldwin

Reputation: 3491

Calling jQuery function too many times in Rails app

In my Rails app, I am committing a single UI action (changing a select value), but the corresponding function is being called twice. The function is below.

    // doc.js
    $(document).on("change", "select.class", (function(){
        if ($("select.otherSelect").find(":selected").is( ":disabled" ) == false) {
            $.ajax({
                  //Ajax call
            });
            console.log("Selector was changed")
        }
    }));

I know the function is being called multiple times because the text "Selector was changed" appears more than once in the JS console when I change the select element only once. Before writing this, changing the select element six times in succession caused the function to be called once, then twice, then four times, then eight times, then sixteen times, then thirty-two times.

Why is this?

Upvotes: 0

Views: 263

Answers (2)

Eric Baldwin
Eric Baldwin

Reputation: 3491

I fixed the issue. To start, I had an entire page whose elements were bound by functions in $(document).ready(function() {. This became problematic because I was using the select to asynchronously replace many elements in the page with new elements that needed to be bound by those functions (but weren't, since the binding only happens once).

To get around this, I copied all the content in $(document).ready(function() { into a function docReady() and then called docReady() both inside $(document).ready(function() { and whenever I asynchronously reloaded the content of the page. This strategy caused my error; now I was binding every element of the page, including the select itself!

Now, I've called the binding functions for the select only once in $(document).ready(function() { and I call the binding functions for the asynchronously generated elements once every time select changes its value.

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can try like this:

$(document).on("change", "select.class", (function(){
if($(this).data('clicked')) {
      return;
  }
        if ($("select.otherSelect").find(":selected").is( ":disabled" ) == false) {
            $.ajax({
                  //Ajax call
            });
            console.log("Selector was changed")
        }
$(this).data('clicked', true);
    }); //removed here was extra )

Upvotes: 0

Related Questions