Search code examples
javascriptjoomla

Javascript in Joomla article or module not executed


I want to use a piece of Javascript to filter tables. I tested the code without CMS and it worked perfectly. However, when I move it to Joomla te Javascript is not recognized/executed. I guess something is blocking or conflicting.

I tried adding the code with Sourcerer and also added it in a module with Flexi code. However, no effect. I read some other posts about this on Stackoverflow, but this was not relevant or no solution.

It's not a programm like RS Firewall that's blocking, and I have also checked the settings of JCE and the article options. All rights for admitting Javascript are okay.

What am I missing here? How can I get it to work?

This is the code:

<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
} 
}
}
</script>

As said, I tested the whole code also outside Joomla and the code itself looks okay. So the combination with Joomla makes it a problem.

Any help is very much appreciated!

Edit: I created a test page: test filter table The Javascript snippet is around line 702 in the source.

Thanks!


Solution

  • The answer is petty simple. You included the necessary code but forgot to call it. The w3c example contains an event binding which I don't see in your source code.

    Example:

    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
    

    Your code:

    <input id="myInput" title="Type in a name" type="text" placeholder="Search for names.." />
    

    You need to call the function myFunction() somewhere. Otherwise, nothing happens. If you can't add this onkeyup directly to the input field, you can use this JavaScript snippet as well:

    $( document ).ready(function() {
        jQuery('#myInput').on('keyup', myFunction);
    });