I've been working with Struts2 and it's JQuery plugin for around a week and I'm a little bit lost.
Last thing I tried to do was to implement searches by date in a jqGrid I'm displaying on a page. For this, I followed this tutorial here.
The thing is it's not working because when I click on the searchfield which is supposed to pop out the datepicker, it won't pop out anything.
I've debugged the javascript code and found that when it tries to call the datepicker() function, an error comes up saying "Uncaught TypeError: Undefined is not a function" .
I'm not sure why this happens as I'm using Struts2-jquery-plugin 3.7.1. I'm posting my JSP code below (I've omitted all the grid rows that don't relate to the question):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<%# taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<sj:head jqueryui="true" jquerytheme="south-street" locale="es" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
datePick = function(elem) {
$(elem).datepicker({
firstDay : 1
});
$('#ui-datepicker-div').css("z-index", 2000);
}
</script>
<title>Testing</title>
</head>
<body>
<s:url var="remoteurl" action="reservationList"/>
<div id="grid">
<sjg:grid
id="reservationsGrid"
caption="%{getText('reservationTable.title')}"
dataType="json"
href="%{remoteurl}"
pager="true"
gridModel="gridModel"
rowList="10,15,30"
rowNum="15"
navigator="true"
navigatorSearch="true"
autowidth="true"
navigatorSearchOptions="{multipleSearch:true, closeAfterSearch:true}">
...
<sjg:gridColumn name="date" index="date" title="Date" search="true" formatter="date" sortable="true" formatoptions="{newformat : 'd/m/Y H:i', srcformat : 'Y-m-d H:i'}" searchoptions="{sopt:['eq','lt','le','gt','ge'], dataInit:datePick}"/>
...
</sjg:grid>
</div>
</body>
</html>
Am I missing any import/reference or such a thing?
UPDATE
Recently I've found a hack, and it's telling me that the issue relates to the datepicker's import/reference:
All I did was adding a new tag inside my JSP:
<sj:datepicker style="display:none" disabled="true"></sj:datepicker>
By doing this, I guess I'm forcing the framework to automatically import and initialize a datepicker, and so it works, but it's not the solution I'm searching for.
So my question then is:
How can I import/reference and initialize the datepicker?
By default <sj:head> will NOT load all jQuery ui resources rather they are loaded on demand. When you've added a <sj:datepicker> tag it also loaded needed resources and your script was able to run.
In order to load all resources at once set loadAtOnce attribute of <sj:head> tag to true.
<sj:head jqueryui="true" loadAtOnce="true"
jquerytheme="south-street" locale="es" />
Related
I am stuck in a situation where I have a Struts2 form with a select tag which when changed should trigger an event and I can't figure out why the onchange function is not triggering but the peculiar thing is that the onchange trigger event works in an other example. I am confused here.
NOT Working:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>New Order</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script type='text/javascript'>
$(function(){
$('#company').change(function() {
var selected = $('#company').val();
alert(selected);
});
});
</script>
</head>
<body>
<s:form action="NewOrder">
<s:select headerKey="-1" headerValue="Select Company" name="company"
label="Select Company" list="{'companies','industries'}" />
Select Item:
<select id="item"></select>
<s:select id="ordertype" name="purchaseorder.orderType"
list="{'Consumables','Tools','Raw Materials'}" label="Order Type" />
<s:textfield name="purchaseorder.orderDate" label="Order Date" />
<s:textfield name="purchaseorder.deliveryDate" label="Delivery Date" />
<s:textfield name="purchaseorder.exciseDuty" label="Excise Duty" />
<s:textfield name="purchaseorder.salesTax" label="Sales Tax" />
<s:textfield name="purchaseorder.remarks" label="Remarks" />
<s:textfield name="purchaseorder.deliverySchedule"
label="Delivery Schedule" />
<s:submit />
</s:form>
</body>
</html>
Working:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$('#state').change(function(){
var sel = $('#state').val();
alert(sel);
});
});
</script>
</head>
<body>
<h3>Struts 2 Dynamic Drop down List</h3>
<s:select label="What's your State" headerKey="-1"
headerValue="Select State" list="states" name="state"
value="defaultState" />
District :
<select id="district"></select>
</body>
</html>
The #something selector (both in jQuery and CSS) is the ID selector. It means:
select the object with the id attribute equals to something.
Since both your <s:select/> have no id attribute set, it should not work in none of the above case.
However, the explanation to why it works there and not here is simple:
Struts2 generates the id for you, when it is not specified. The id is usually autogenerated in the form of formName_elementName (or formId_elementName, I'm not sure).
First example:
since you have a form, the id of your select will be something like id="form1_company" (or id="formNewAction1_company", I don't remember the way Struts2 generates the id/name for the forms, since also your <form> is missing them !..).
Second example:
the <s:select> is not enclosed in a form, so since its name is "state", the autogenerated id will be id="state" , and will be matched by the $('#state') selector.
Moral of the story:
always give your objects an id, at least to the one you need to work with JavaScript.
$(function(){
$('#ordertype').change(function() { //id shoud be orderType not company
var selected = $('#ordertype').val();
alert(selected);
});
});
Firstly I do not see any element that matches #company in the first HTML, BUT I also don't see one that matches #state in the supposedly working example.... so that's confusing. You have a "select[name=company]" but no select box has an id attribute with value 'company'.
If anything is being dynamically changed on your page, like something loading through ajax (like that id attr being added in) you may need to use this: .on()
I am trying to call jsp code in javascript.
The error is as follow
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 16 in the jsp file: /testng_index.jsp
String cannot be resolved
13: var mai=document.getElementById("j");
14: //mai.value = mai.value.toUpperCase();
15: var m=mai.value;
16: <%=String value=document.writeln(m)%>
17: var mo= <%= new PlaneBo().getOwnerId(value)%>;
18: // document.writeln(mo);
19: if(mo==0)
here is the code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.ams.services.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function emailCheck()
{
var mai=document.getElementById("j");
//mai.value = mai.value.toUpperCase();
var m=mai.value;
<%=String value=document.writeln(m)%>
var mo= <%= new PlaneBo().getOwnerId(value)%>;
// document.writeln(mo);
if(mo==0)
{
// document.writeln(m);
var tab = document.getElementById("t");
var row = tab.insertRow(3);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var inpt= document.createElement("input");
inpt.setAttribute("name","jho");
inpt.setAttribute("type","text");
cell1.innerHTML="Name";
Please provide me suitable solution of this problem.
It looks to me as if you have some confusion about when and where Java and JavaScript code executes.
The Java code and JSP runs on the server when the browser requests the page. The server knows nothing about HTML and JavaScript. As far as the server is concerned, this is your JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.ams.services.*" %>
TEXT
<%=String value=document.writeln(m)%>
TEXT <%= new PlaneBo().getOwnerId(value)%>
TEXT
The server doesn't really care what's in the sections marked TEXT; it just sends them straight to the browser as they are. But it does care about what's in the <%# ... %> and <%= ... %> tags.
You get an error because the server doesn't understand document.writeln(m). It's not aware of any object named document, so it can't evaluate document.writeln(m). It happens that in JavaScript there is an object document and a function document.writeln, but that's irrelevant. The server doesn't know anything about JavaScript.
The JavaScript code doesn't execute until the page has finished being sent to the browser. You haven't shown when the function is called: it may be after an input field's value has been changed or a button has been clicked. The JavaScript runs in the browser, not on the server, so it can't directly call the Java code on the server.
If you really want to execute some Java code on the server during a call to your JavaScript function, you will need to use an AJAX call. See this question for more information on how to do this.
I have the following code snippet in JSP page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html; charset=iso-8859-1" language="java"
import="java.util.*,java.sql.*,javax.naming.*%>
<html>
<head>
......
.......
When I tried to add
<!DOCTYPE html>
to top of page, I am getting the following error
Unable to get value of the property 'value': object is null or undefined
What could be the reason for this and how to resolve this error?
Scripts block
<script>
function myFunc() {
if (prod.value.length > chars) {
prod.value = prod.value.substring(0, chars);
alert('Exceeded');
}
}
</script>
Adding <!DOCTYPE html> shifts the browser into Strict Mode, which means it has narrower tolerances for common coding errors in addition to having slightly different CSS behaviour.
It sounds like you have a <script type="text/javascript"> on your page which uses an obsoleted or deprecated technique for getting input values.
I suggest using a Script Debugger (IE, Chrome, Safari and Firefox all feature script debuggers, all accessed by pressing F12) and stepping through your scripts to find the cause of the error and then fixing it yourself.
I'm trying to reload a target div from a javascript by using jquery to target the div and a struts action that loads the content.
Does anyone know how to do this?
The problem is how I use (javascript) jquery to do this.
BR, Tobias
The simplest thing to do is use the jQuery .load() function.
$('#targetDivId').load('${your.struts.url}', function() {
// stuff to do when the div has been reloaded
});
Now understand that you should make sure that the response from your action is a page that's not really a complete HTML page, because you can't stuff a complete HTML document inside a <div>. If you have a complete document, and you only want a portion of it (say, a block contained within a <div> with id "usefullStuff"), you can do this:
$('#targetDivId').load('${your.struts.url} #usefullStuff', function() {
// code
});
Or with Struts2 jQuery Plugin:
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head/>
</head>
<body>
<div id="div1">Div 1</div>
<s:url id="ajaxTest" value="/AjaxTest.action"/>
<sj:a id="link1" href="%{ajaxTest}" targets="div1">
Update Content
</sj:a>
</body>
</html>
I have found several other questions here on S.O. (and the web in general) that ask roughly this same question, but the answers always seem to suggest other ways of structuring code that avoid the need for addressing this underlying issue.
For example, many people suggest (and a good suggestion, I agree) to put your code in the jquery load method's callback, on the calling page and not the called page. However I have unique scripts that may appear in certain resources, so I would not want to do that for every load and nor do I necessarily know what these scripts will be.
Here is a test setup to demonstrate what I'm trying to do. The short summary is that when I load partial.htm from main.htm, its script does not fire.
main.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>main file</title>
</head>
<body>
<ul id="links">
<li>some page1</li>
<li>some page 2</li>
<li>some other partial page</li>
</ul>
<div id="panel" style="display:none; padding:20px; background-color:#CCC;">
LOADED CONTENT WILL GO HERE
</div>
<script type="text/javascript" src="/path/to/jquery-1.3.2.min.js"> </script>
<script type="text/javascript">
$(function(){
$('#links a').click(function() {
var $panel = $('#panel');
$panel.show();
$panel.html('Please wait...');
var href = $(this).attr('href');
$('#panel').load(href + ' #content');
return false;
});
});
</script>
</body>
</html>
OK, very simple functionality on this page. Imagine there are many more links, and some of them may require scripting while others do not.
Here is partial.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>partial file</title>
</head>
<body>
<div id="content">
<p>Hey, I am the partial file!</p>
<script type="text/javascript">
alert('I am some JS in the partial file! But sadly I do not execute...');
</script>
</div>
<div>
I am some other content on the page that won't be included by jquery.load()...
</div>
</body>
</html>
Notice that my script in partial.htm does not fire. So, my question remains: how to get this to fire, excluding any answers that tell me to put this in the .load() method's callback. (This would be because I may not have the fore-knowledge of which scripts these partial pages may contain or require!)
Thank you!
Update #1:
I suppose an acceptable answer is simply "you can't." However, I'd like to know if this is definitively the case. I haven't been able to find anything that officially states this yet.
Also, when I use firebug to inspect the panel region afterwards, there is no script element present at all. It is as if it is being parsed out by load.
Update #2:
I've narrowed this down to be a problem only when using the selector as part of the href. Loading the entire "somepage.html" will execute the script, but loading "somepage.html #someregion" does not.
$panel.load('somepage.html'); // my script fires!
$panel.load('somepage.html #someregion'); // script does not fire
I'm going to try and hunt down why this may be the case in the jquery source...
Well it seems that this is by design. Apparently to make IE happy, the rest of us suffer. Here's the relevant code in the jquery source:
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
I'm wondering if, instead of just stripping out the scripts, I could modify the jquery source to include them in some other way that makes IE happy? I still have yet to find anything else on the web discussing this matter, I'm sure I'm not the only person stumped by this?
I have run across issues before with IE not running injected <script>s that didn't contain the defer attribute. This discussion thread has some good information about the topic: innerHTML and SCRIPT tag