8

I have a piece of jQuery code which I found on the internet and I want to integrate it to my jsp page, I use Spring form tags.

Here is the jQuery code:

(function ($) {
    //тут превращаем select в input    
    var id = "test",
        $id = $('#' + id),
        choices = $id.find('option').map(function (n, e) {
            var $e = $(e);
            return {
                id: $e.val(),
                text: $e.text()
            };
        }),
        width = $id.width(),
        realClass = $id.get(0).className,
        realId = $id.get(0).id,


        $input = $('<input>',{width: width});
    $id.after($input);
    $id.hide();
    $id.find('option').remove();
    //превратили

    $input.select2({
        query: function (query) {
            var data = {}, i;
            data.results = [];

            // подтставим то что искали

            if (query.term !== "") {
                data.results.push({
                    id: query.term,
                    text: query.term
                });
            }

            // добавим остальное

            for (i = 0; i < choices.length; i++) {
                if (choices[i].text.match(query.term) || choices[i].id.match(query.term)) data.results.push(choices[i]);
            }

            query.callback(data);
        }
    }).on('change',function()
          {   
              var value=$input.val();
              $id.empty();
              $id.append($('<option>').val(value))
              $id.val(value);             
          }
         );
})(jQuery);

CSS file for jQuery - I name it test.css and apply it to my jsp page:

#test {
    width: 300px;
}

My jsp page

 <html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<title>Страница выборки</title>
<link rel="stylesheet" href="resources/cssFiles/jquery-ui.css"/>
<link rel="stylesheet" href="resources/cssFiles/test.css"/>
<script type="text/javascript" src="resources/jsFiles/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="resources/jsFiles/jquery-ui.js"></script>
<script type="text/javascript" src="resources/jsFiles/jquery-ui-i18n.js"></script>
<script type="text/javascript" src="./resources/jsFiles/selecter.js"></script>
<script type="text/javascript">

 $(document).ready(function()
         {

         $("#parctdate, #chldAdmitDate, #chldSchlDate, #name, #type, #daySchdl, #workSchdl, #rotation, #numbch, #chUnder3, #chUpper3, #chGoSchool, #chAdmitted").mouseenter(function() {        
             $(this).css("background-color", "gainsboro");   
         });

         $("#parctdate, #chldAdmitDate, #chldSchlDate, #name, #type, #daySchdl, #workSchdl, #rotation, #numbch, #chUnder3, #chUpper3, #chGoSchool, #chAdmitted").mouseleave(function() {        
             $(this).css("background-color", "white");   
         });

         var enabledDays = ["6-1-2013", "7-1-2013", "8-1-2013", "9-1-2013", "10-1-2013", "11-1-2013"];
         function nationalDays(date) {
                var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();            
                for (i = 0; i < enabledDays.length; i++) {
                    if($.inArray((m+1) + '-' + d + '-' + y,enabledDays) != -1 || new Date() > date) {           
                        return [true];
                    }
                }
                return [false];
            }

         $(function(){
               $.datepicker.setDefaults($.extend($.datepicker.regional["ru"]));
               $("#datepicker1, #datepicker2, #datepicker3").datepicker({dateFormat: "yy-mm-dd",
                                                                         duration: "normal",
                                                                         numberOfMonths: [ 1, 2 ],
                                                                         constrainInput: true,
                                                                         beforeShowDay: nationalDays});   
             });         


     });

</script>

</head>

<body>

<spring:message code="label.input.button" var="labelbutton"/>

<h3 align="center"><spring:message code="label.input.topLabel"/></h3>


<form:form  id="myform" cssClass="testClass" modelAttribute="fboAttribute" method="post" action="add" >
<table align="center">  


<tr id="name">
<td><form:label path="institution.nameOfInstitution"><spring:message code="label.input.nameOfInstitution"/></form:label>
<form:select id="test"  path="institution.nameOfInstitution"> 
<form:option  value=""><spring:message code="label.select.msg" />-</form:option>
<form:options items="${listOfInstitutionsNames}"/>
</form:select> 

<tr>
<td><input type="submit" value="${labelbutton}"/></td>

</table> 
</form:form>

I would like to integrate my jQuery scripts with my jsp and Spring form tags.

I'm sorry I'm new in jQuery.

Thank you

11
  • Hi, by integrate you mean what ? Commented Jun 29, 2013 at 10:26
  • Hello sir. I want to integrate jQuery+CSS to my JSP(last my question tab exactly is <form:select id="test" path="institution.nameOfInstitution">) But I have confused because I did not work with jQuery before. So insted <form:select id="test" path="institution.nameOfInstitution"></form:select> and all what between select tag I want to use jQuery. code And as you can see I have <form:options items="${listOfInstitutionsNames}"/> this is my attributes ${listOfInstitutionsNames} fetching and I want put them in jQuery code insted used in jQuery attributes -var test- example. Commented Jun 29, 2013 at 10:43
  • jQuery is a JavaScript library. You shouldn't add HTML code with jQuery. I don't know what you mean by integrate... but you can add the script to the page like this: <script src="path_to_jquery"></script> Commented Jun 29, 2013 at 10:54
  • Yes sir... I mean instead of my <form:select> use this jQuery code. And make my attributes appears in jQuery code. My attributes are this ${listOfInstitutionsNames}. Where to add them in jQuery code. and I need iterate over this ${listOfInstitutionsNames} attributes. Commented Jun 29, 2013 at 11:12
  • @java_user : do you know how to add jQuery to a a usual HTML page ? If so, there's not much difference between doing that in JSP and HTML. In fact, jQuery is just like any JS (javascript), you can use it in whichever tag in your HTML (be it Spring or not). Commented Jun 29, 2013 at 11:14

3 Answers 3

4

jQuery, like any JavaScript, is added in a <script> tag in the <head> tag of your JSP page. You either add all the code or just a link to the .js file containing your jQuery, like for example :

<script src="./libs/jquery/1.10.1/jquery.min.js"></script>

Having done that, you want now to leverage your jQuery in the HTML tags, you do that as for any HTML page. Namely, in your case, you don't have to take away the spring tags. Let it generate the select/options via your ${listOfInstitutionsNames}, just add class="testclass" to your spring form tag, like this :

<form:form  cssClass="testclass" id="myform" modelAttribute="fboAttribute" method="post" action="add" >

When rendering the form on a browser, Spring will include in the generated HTML the class attribute with value of testclass.

Hope that helps, best of luck.

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

2 Comments

Thank you for answer.... I did like you said it doesn't work. Oh. I don't have class I have cssClass instead in Spring forms. I edit my question above for you
what is inside jquery.min.js file? Is this a standard file we need to put in our web project and use jQuery functions under <script type="text/javascript"> </script> ?
1

For Dynamic Web Project(designed using MVC Model)

Add like this in head section:

<script type="text/javascript" src="${pageContext.request.contextPath}/jQuery.js"/></script>

I kept my jQuery.js in WebContent folder(with jsp pages).

1 Comment

what is there inside jQuery.js file? Is this a standard file we need to put in our web project and use jQuery functions under <script type="text/javascript"> </script> ?
1

if what you mean is that you want to bind Java side information to JS var, you can do as I did:

  1. At Java side, use Google's Gson to encode Java object to Json string.

  2. At Java side, use org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(String) to make you Json string escaped as JavaScript.

  3. At JSP side, do something like this:

    <script>
    var jsonObject = JSON.parse("<%=yourJsonString%>");
    </script>

Comments

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.