0

I have a javascript function in my asset tree. It takes the input from the user and then filters a table of data by that input. However, I cannot get it to work in my index.html.erb file from my asset/javascript pipeline. I can put the function in script tags in the index.html.erb page and it will work. I can also put an alert("test") in my javascript file and it will work in index.html.erb. Can someone take a look and tell me what piece I am missing?

// # Place all the behaviors and hooks related to the matching controller here.
$('document').ready(function(){
  var stateInput, stateFilter, table, tr, td, i;
  stateInput = document.getElementById("stateInput");
  stateFilter = stateInput.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

 // Loop through all table rows, and hide those who don't match the search query
  function stateSearch() {
    for (i = 0; i < tr.length; i++) {
      td = tr[i].getElementsByTagName("td")[0];
      if (td) {
        if (td.innerHTML.toUpperCase().indexOf(stateFilter) > -1) {
          tr[i].style.display = "";
        } else {
          tr[i].style.display = "none";
        }
      }
    }
  }
}); 

Here is my index.html.erb. I only include the input tag because I am assuming it's all you need.

<input id="stateInput" type="textbox" placeholder="State ID ex. IN" onkeyup="stateSearch()">

1 Answer 1

1

Try something like this:

(function ($) {
    
      stateSearch = function() {
        alert( "stateSearch called." );
        // write your logic here
      }
    }) (jQuery);
    
    $('document').ready(function() {
      var myTextBox = $("#stateInput");
    
      myTextBox.on('change', function() {
        stateSearch();
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="stateInput"/>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that calls an alert every time I enter something into the search box. I think I can find the solution from here. Thanks Jiggneshh!
Also your implementation is using low-level JS constructs. You are using jQuery then you should use its API to find the elements, filter etc. I am not a JS expert but I think in your original version you defined the function inside the ready function and hence it was never found to be available. You should keep an eye on browser's developer console for any errors related to JS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.