Grails Javascript Example

By , last updated July 31, 2019

In this article we will show how to include JavaScript library as an asset in grails GSP file to dynamically filter results in a HTML table.

We will create a test application that will pull a set of usernames from a service and show it in a HTML table. We will then make a simple search functionality that will filter usernames dynamically with JavaScript.

Here’s a screenshot of the resulting application:

In this tutorial we will use the Grails framework.

Grails is an open source web application framework which is based on the Java platform or Groovy. This programming framework is inspired by Ruby on Rails. It is meant to be highly reproductive as it promotes “coding by convention”.

It is used to build web applications that run on Java Virtual Machine (JVM). Grails provide a standalone development environment. It hides much of configuration details from the development.

Create new Grails file GSP

In order to use JavaScript with grails we will create a new Grails file with extension .gsp.

GSP stands for Groovy Server Pages and is a type of file where we put HTML code that will be rendered and shown to users.

We place the new file under the views folder in our Java-project. It’s called show.gsp. We included a Bootstrap.css file to style our page.

GSP files are much like usual HTML files with some extra Grails tags. In our table we will use the loops tag g:each that will help us loop through the users list.

Links to JavaScript libraries are placed at the bottom of the HTML file right before the closing body tag.

show.gsp:

<!DOCTYPE html>
<html>
    <head>
	<title>My table</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
	<asset:stylesheet src="bootstrap.css"/>
    </head>
    <body>
    <h1>My table</h1>
    <form>
        <div class="form-group">
            <input id="searchInput" value="Type To Filter">
        </div>
    </form>
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>Username</th>
            </tr>
            </thead>
            <tbody id="fbody">
            <g:each in="${usersList}" var="user">
            <tr>
                <td>${user.name}</td>
            </tr>
            </g:each>
            </tbody>
        </table>
    <asset:javascript src="jquery-2.2.0.min.js"/>
    <asset:javascript src="filter.js"/>
	</body>
</html>

As you can see in the code above, GSP files are much like usual HTML code. You have a head where you place meta tags and links to CSS assets. A body tag has all the information that will be rendered to users.

In this example we will show a list of all our users and filter them out based on their names.

First, we create a table with all users names, one per each line. Over the table we placed a search field where a user will be able to filter names based on character input.

Include JavaScript

We have now created a HTML file with many usernames that we need to dynamically filter based on user input.

For this purpose we will use JQuery and our own JavaScript file that we will call Filter.js.

Filter.js will search all the names and show only those containing input letters:

Filter.js:

$("#searchInput").keyup(function () {
    var data = this.value.split(" ");

    var jo = $("#fbody").find("tr");
    if (this.value == "") {
        jo.show();
        return;
    }

    jo.hide();

    jo.filter(function (i, v) {
        var $t = $(this);
        for (var d = 0; d < data.length; ++d) {
            if ($t.is(":contains('" + data[d] + "')")) {
                return true;
            }
        }
        return false;
    })
    .show();
}).focus(function () {
    this.value = "";
    $(this).css({
        "color": "black"
    });
    $(this).unbind('focus');
}).css({
    "color": "#C0C0C0"
});

JSFiddle with filtering rows in a HTML table example.

Create the Controller

We will need to create a new controller for our application. You may use one of the existing controllers in your project as well.

If you are creating a new controller, you can use Grials command line interface by typing:

Create-controller TableController

This command creates a new controller in your project with the name TableController.

Open this new controller and create a new method show. This method will get all the users from a service and return a list of usernames into our show.gsp file:

TableController.groovy:

def show() {
        def users = someService.getAllUsers()

        return [usersList:users]
    }

Run the application. At this point it should work.