jQuery adding to JSP page - javascript

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

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.

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).

if what you mean is that you want to bind Java side information to JS var, you can do as I did:
At Java side, use Google's Gson to encode Java object to Json string.
At Java side, use org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(String) to make you Json string escaped as JavaScript.
At JSP side, do something like this:
<script>
var jsonObject = JSON.parse("<%=yourJsonString%>");
</script>

Related

Cant submit html form after use js script

I have this html site
<html>
<head>
<link rel="stylesheet" href="~/Content/index.css" />
<link rel="stylesheet" href="~/Scripts/fancyBox/source/jquery.fancybox.css" type="text/css" media="screen" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="~/Scripts/prototype.js"></script>
<script type="text/javascript" src="~/Scripts/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="~/Scripts/Scale.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="~/Scripts/fancyBox/source/jquery.fancybox.pack.js"></script>
<title>Countries</title>
</head>
<body>
<div>
#foreach (var country in Model)
{
<a class="fancybox">
<div class="tooltip">
#using (Html.BeginForm("ChangeCulture", "Home", new { lang = country.Culture }))
{
<!-- onclick="zoomIn('#country.Culture')"-->
<input id="#country.Culture" class="#country.Sprite" type="image" name="submit" src="//" />
<span class="tooltiptext">#country.Country</span>
}
</div>
</a>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
this.find("form").submit();
}
});
})
</script>
</body>
</html>
The bottom line is that the flags of countries with tooltips are displayed on the screen and by pressing it is necessary to change the language of the tooltips to the language used in the country. I did this, and now I need to increase the whole screen after receiving the picture with the flag, and then the language would change. I found the fancybox scripts, but after it is inserted, the form is not sent, the selected flag appears in the center, but nothing happens after that, what could be the problem? I have not written to asp and js before
After click on the image I got an error
Uncaught TypeError: this.find is not a function
at Object.afterShow (Index:119)
at Function.trigger (jquery.fancybox.pack.js:17)
at HTMLDivElement._afterZoomIn (jquery.fancybox.pack.js:33)
at HTMLDivElement.d.complete (jquery-latest.min.js:4)
at j (jquery-latest.min.js:2)
at Object.fireWith [as resolveWith] (jquery-latest.min.js:2)
at i (jquery-latest.min.js:4)
at m.fx.tick (jquery-latest.min.js:4)
My method
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
var cookie = this.Request.Cookies["lang"];
if (cookie != null)
{
cookie.Value = lang;
}
else
{
cookie = new HttpCookie("lang")
{
HttpOnly = false,
Value = lang,
Expires = DateTime.Now.AddYears(1)
};
}
this.Response.Cookies.Add(cookie);
return this.Redirect(returnUrl ?? "Index");
}
You should user jquery selector
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
$(".fancybox").submit();
}
});
})
The error is located in this statement:
this.find("form").submit();
You're trying to call find() method on plain JS object inside this wrapper, where the function belongs to a jQuery object. The correct way is using jQuery object like this:
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
// alternative: use $(this).closest("form").submit();
$(this).find("form").submit();
}
});
});
</script>
Additionally your redirection method in controller action should be like below, since Controller.Redirect requires full path or URL for redirect to another page:
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
// cookie settings here
if (string.IsNullOrEmpty(returnUrl))
{
return this.RedirectToAction("Index");
}
return this.Redirect(returnUrl);
}
The this in this.find("form") is not $(".fancybox") here.
Try using $('.fancybox form') instead.

Edit html div that has been copied into html file with jquery load

So I have a website with a Header.html. In the header are three buttons. I've copied the Header.html into all of my other pages with jquery's load. Now what I would like to do is change the colour of one of the buttons depending on the page it's on. But when I use document.GetElementById in javascript it can't find the div of the button I've copied from the Header.html
Here's the Header.html
<div id="Header_Wrapper">
<div id="Header_PageLinksWrapper">
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_Games" href="..\Pages\Games.html">Games</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_AboutMe" href="..\Pages\AboutMe.html">About Me</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_CV" href="..\Pages\CV.html">CV</a>
</div>
</div>
</div>
The javascript file:
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html");
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
}
);
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = document.getElementById(id);
if (divElement == null)
{
console.log("Could not find element " + id);
}
divElement.style.color = 0xffffff;
}
One of the pages (eg. Games.html)
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Adabelle Combrink - Games</title>
<link rel="stylesheet" type="text/css" href="..\Templates\Header.css"/>
<link rel="stylesheet" type="text/css" href="..\Templates\Page.css"/>
<link rel="stylesheet" type="text/css" href="..\Pages\Games.css"/>
<script type="text/javascript" src="..\Scripts\jQuery.js"></script>
<script type="text/javascript" src="..\Scripts\Defaults.js"></script>
</head>
<body>
<header>
<div id="Header"></div>
</header>
</body>
</html>
What this gives me in the console is Could not find element PageLink_Games. I don't get that error if I use something that is in Games.html like Header.
Is there any other way of doing the same thing. I know you can include files into eachother with php but I haven't gotten that right and don't seem to be able to run .php files in Visual Studio.
jQuery.load has a success callback. Use it to assure your code is only executed after the loading is complete.
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", null, function() {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
Also your SetPageLinkColours function can be improved with jQuery:
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = $("#"+id);
if (!divElement.length)
{
console.log("Could not find element " + id);
}
else
{
divElement.css('color','white');
}
}
load function makes async request , so your code tries to find element before it rely appears. U need to use load function callback http://api.jquery.com/load/
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", function () {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);

Javascript/JSON error: not well formed

I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')

jQuery clone() copies data...sometimes...?

Using the sample below, I have a tr that I am duplicating. It contains a jQuery autocomplete. The first time it is cloned, the auto complete functionality does not work because the attached data("items") is null. The second time the Add button is clicked, the autocomplete works. Thereafter, clicking Add once again produces a non-functioning autocomplete.
Adding a breakpoint inside of the makeAutoComplete function shows that items is always null except for when clicking Add the second time!
Can anyone explain this strange behavior?
HTML/JS (Fiddle here: http://jsfiddle.net/SDvF4/12/)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test!</title>
<style type="text/css">
tr.Template
{
display: none;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.18/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var textbox = $(".AutoComplete");
makeAutoComplete(textbox);
$("#addButton").click(function ()
{
var attrRegex = /\d+/;
var template = $("tr.Template");
var newRow = template.clone(false);
var newRowIndex = (template.siblings().length + 1);
newRow.removeClass("Template");
newRow.find("*[id]").each(function ()
{
var element = $(this);
element.attr("id", element.attr("id").replace(attrRegex, newRowIndex));
});
newRow.find("*[name]").each(function ()
{
var element = $(this);
element.attr("name", element.attr("name").replace(attrRegex, newRowIndex));
});
newRow.insertBefore(template);
newRow.find(".AutoComplete").each(function ()
{
makeAutoComplete($(this));
});
});
});
function makeAutoComplete(textbox)
{
var items = textbox.data("items");
var test = textbox.data("test");
if (items == null)
{
if (test == "JSM")
alert("ERROR: data.items not copied but data.test was!");
else
alert("ERROR: data.items not copied nor was data.test!");
}
textbox.autocomplete(
{
minLength: 0,
source: items
});
}
</script>
</head>
<body>
<table>
<tbody>
<tr class="Template">
<td>
<input id="test_0" name="test_0" class="AutoComplete" type="text"/>
<script type="text/javascript">
var testData = [{ label: "One", value: 1 }, { label: "Two", value: 2 }];
$("#test_0").data("items", testData);
$("#test_0").data("test", "JSM");
</script>
</td>
</tr>
</tbody>
</table>
<br/><br/>
<button id="addButton">Add</button>​
</body>
</html>
There were multiple issues I had to fix to get this to work.
First was pointed out by #pimvdb - I wasn't IDing the elements correctly so the second new row had the same ID as the template row.
Second, you can't simply call autocomplete on a widget that is already an autocomplete - first you have to destroy it:
textbox.autocomplete("destroy");
textbox.removeData("autocomplete");
The 12th revision works correctly: http://jsfiddle.net/SDvF4/12/

How do you use $('document').ready(function()) in jQuery?

I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}].
I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});});
});
</script></head>
<body><form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" /></form></body>
</html>
Short version (suggested by meeger): don't use single quotes around document.
document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.
$(document).ready(function() {
You'll also want to take the onLoad attribute off of the body tag, else it will run twice.
Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.
It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
EDIT:
I tested with the following and mocked the json object since I can't make that call myself.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
Here it is in all its glory. The shorthand, awesome version:
UPDATED
<script type="text/javascript" language="javascript">
$(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var cacheFruits = $('#fruits'),
cacheOption = $(document.createElement('option'));
$.each(jsonData, function (i, j) {
cacheFruits.append(
cacheOption.clone().attr('value', j.options).html(j.options)
);
});
});
});
</script>
Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.
There should be no reason why the above would not work.
You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
$(this).each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});
});
});
Try this, your json data should be in this format:
[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var options = [];
$.each(jsonData, function (i, j) {
options.push('<option value="' + j.value + '">' + j.text + '</option>');
});
$('#fruits').html( options.join(''));
});
});
Please note that there may be an encoding/escaping issues here.
Make sure that you escape the text properly from the server side.
htmlentities, htmlspecialchars can help you with that.
This should work in most browsers

Categories