0

I want to replace this:

<body onload="
      $('input[name=startDate]').focus();
      $(function () { 
        $('#startDate').datepicker({ dateFormat: 'mm/dd/yy'});
      });
 ">

with inline javascript - something like:

<script th:inline="javascript">
/*<![CDATA[*/
    $( document ).ready(function() {
        $('input[name=startDate]').focus();
        $('#startDate').datepicker({ dateFormat: 'mm/dd/yy' });
    });
/*]]>*/
</script>

However, this doesn't work. The error is: ReferenceError: $ is not defined

Anyone knows how to get this to work?

Reporter
  • 3,897
  • 5
  • 33
  • 47
ibhana
  • 151
  • 1
  • 9

3 Answers3

2

Have you done this :

Your controller class:

@Grab("org.webjars:jquery:2.1.1")
@Grab("thymeleaf-spring4")
@Controller
class MyApp{...}

Your html (tymeleaf)

    <head>
          <title>blablabla</title>
          <script src="webjars/jquery/2.1.1/jquery.min.js"></script>

 <script th:inline="javascript">
/*<![CDATA[*/
    $( document ).ready(function() {
        $('input[name=startDate]').focus();
        $('#startDate').datepicker({ dateFormat: 'mm/dd/yy' });
    });
/*]]>*/
</script>
            </head>
AchillesVan
  • 4,156
  • 3
  • 35
  • 47
  • This was nearly the correct answer, which I've enhanced in my own response to include the spring configuration class. Thanks. – ibhana Jul 26 '16 at 10:22
2

Thanks to the hints above I was able to solve this as follows:

Add the appropriate dependency:

<dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>2.2.4</version>
        <scope>compile</scope>
</dependency>

Add a configuration hook:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }
}

Finally, import the script correctly:

<script th:src="@{/webjars/jquery/2.2.4/jquery.min.js}"></script>

The jQuery ready function is then called correctly in the inline javascript.

ibhana
  • 151
  • 1
  • 9
1

please add:

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

before your script block.

$ is part of jQuery. You need to add it's library/implementation file for to use it.

user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62