user3106974
user3106974

Reputation: 110

Adding JQuery to java servlet

  out.println("<html>");
    out.println("<head>"
            + "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"></script>"
            + "<script>"
            + "$('input[type=\"checkbox\"]').on('change', function(){$('input[type=\"checkbox\"]').not(this).prop('checked', false);});"
            + "</script>"
            + "</head>");
    out.println("<body>");

I want to check only 1 checkbox at a time and would like to use this script to do that. The script itself is working, however in the servlet it isn't.

How can i add this script to the servlet?

Upvotes: 0

Views: 755

Answers (2)

Neeraj Jain
Neeraj Jain

Reputation: 7730

You can wrap up your JQuery code inside a function so that it will be executed once your document is ready not before that like this :

$( document ).ready(function() {
$('input[type=\"checkbox\"]').on('change', function(){$('input[type=\"checkbox\"]').not(this).prop('checked', false);});
});

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100209

It's unlikely a servlet problem. You execute your jQuery code before the page body is loaded, thus you have no checkboxes yet and your events are not registered. Try to wrap it into $(function() {...}).

out.println("<html>");
out.println("<head>\n"
        + "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"></script>\n"
        + "<script>\n"
        + "$(function() {\n"
        + "  $('input[type=\"checkbox\"]')\n"
        + "    .on('change', function(){$('input[type=\"checkbox\"]').not(this).prop('checked', false);});\n"
        + "});\n"
        + "</script>\n"
        + "</head>");
out.println("<body>");

Upvotes: 1

Related Questions