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()
Related
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" />
I have the following piece of code :
<sx:datetimepicker name="dateOfBirth" id="dateOfBirth"
displayWeeks="5" displayFormat="dd/MM/yyyy" onchange="test()"/>
But for this the onChange event does not work, although I have a simple javascript function like this:
<script>
function test(){
alert('hi-----');
}
</script>
Note: I read somewhere that it is a bug in Struts that the onChange event doesn't work for DateTimePicker. However I am not sure about it. Is there any workaround discovered for it?
Dojo tags are deprecated. Use jQuery tags. You can find more about struts2-jquery-plugin. You should use datepicker tag.
<%# taglib prefix="sj" uri="/struts-jquery-tags" %>
<head>
<link href="<s:url value="/css/template_styles.css"/>" type="text/css" rel="stylesheet">
<sj:head jqueryui="true" />
<title></title>
</head>
<script type="text/javascript">
$.subscribe('changeTopic', function(event,data) {
alert('Date : '+event.originalEvent.dateText);
});
</script>
<sj:datepicker name="dateOfBirth" id="dateOfBirth" label="DOB" displayFormat="dd/MM/yy" onChangeTopics="changeTopic"/>
Hello I came across a weird behavior with an onclick attribute regarding form submission.
Page on Server:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-us" >
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Return Form Example</title>
<script type="text/javascript">
function doSomething(){
alert("hey");
return false;
}
</script>
</head>
<body>
<form action="submit.php" method="post">
<input type="submit" onclick="return doSomething()" value="click me!">
</form>
</body>
</html>
In this example, running on my server, when I click the submit button I get an alert saying hey and I stay on the current page. However, I tried to set this same example up on jsfiddle and I get an 404 error meaning the form was submitted. I cannot figure out why this occurs.
Here is the jsfiddle where I am trying to replicate the behavior on my server.
jsfiddle:
http://jsfiddle.net/46XSv/
You want to check the option "no wrap - in <head>" which is "Do not wrap the Javascript code, place it in section".
Select "no wrap - in <head>" under "Framework and extensions"
In this page you'll find the description of each of the options around the bottom: http://doc.jsfiddle.net/basic/introduction.html.
Also its a good practice to include semicolon at the end of your return statement, like the following:
<input type="submit" onclick="return doSomething();" value="click me!">
You should use onsubmit on the <form> element instead of onclick on the <input> element. It will work correctly.
Ok its a continuation of my crap attempts of using client side scripts along with server side elements.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<form name="test" action="test.jsp" method="post" enctype="multipart/form-data">
<select name="harish" onchange=callme();>
<option value="1">1</option>
<option value="2">2</option>
</select>
<script>
var jsvar="Hello";
function callme()
{
alert(jsvar);
jsvar=document.getElementById("harish").value;
alert(jsvar);
}
</script>
<%
String s=(String)("<script>document.writeln(jsvar)</script>").toString();
out.println(s.equals("Hello"));
if(!(s.equals("Hello")))
{
String jspvar="<script>document.writeln(jsvar)</script>";
out.println("jspvar"+jspvar);
session.setAttribute("test",jspvar);
}
%>
</form>
</body>
</html>
Now what I am trying is to set the selected value as a session variable.But my bad the value from javascript is not sitting properly on the jsp/java variable and therby my condition if(!(s.equals("Hello"))) fails.Can anyone help me here...
Update:
Can the below be the solution for this question
Have a HTML page with two frames. Let the first page contain all the javascript values you wish to populate. The second page(hidden) of the frame actually does the trick. That is actually a JSP. On click of a button (on any action on the first page) in the first page, point your location to the hidden frame (2nd page), perform checks / conversions and populate the variable of the first page using cross frame JAVASCRIPT.
my condition if(!(s.equals("Hello"))) fails
That is because this:
String s=(String)("<script>document.writeln(jsvar)</script>").toString();
out.println(s.equals("Hello"));
...is pretty much the same as writing:
out.println("this".equals("that"));
It will always be false.
Now what I am trying is to set the selected value as a session variable.
To set a variable in the session, you need to POST the form to the server (ignoring AJAX techniques, etc.). As I mentioned here, using multipart/form-data requires a MIME parser - the form below uses the default enctype.
This form will, when you select an option from the drop-down, post the form to the server. Every time the JSP is run, it uses a scriptlet <% ... %> tests to see if a "harish" parameter has been posted. If it has, it places it in the session. An expression <%= ... %> is used to display the current session value.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- header removed for clarity -->
<body>
<form id="test" name="test" action="test.jsp" method="post"><select
name="harish" onchange="document.getElementById('test').submit();">
<option value="select">select an option</option>
<option value="1">1</option>
<option value="2">2</option>
</select></form>
<%
//see if a parameter was sent from page; "harish"==name attr on select
String value = request.getParameter("harish");
if (value != null) {
//store it in session
session.setAttribute("test", value);
}
%>
<%="harish=" + session.getAttribute("test")%>
</body>
</html>
This assumes that the above page is test.jsp - that the page posts back to itself. If not, you'll need to move the scriptlet and the expression to test.jsp.
Java is evaluated on the server side, so in variable s you will always find
<script>document.writeln(jsvar)</script>
Javascript is evaluated on the opposide side, that is on the client's browser, so this is why your method does not work (I've fallen many time into this also ^^)
You can POST the form on the same jsp where this code resides and take the result from the POSTed data, to do that you'll use a scriptlet. If I remember correctly you could use
request.getParameter("PARAMETER_NAME")
So just add the name of the jsp where this code is to the action of the form and the above code to retrieve the selected value.
I have a page where I am getting session values then calling form action through javaScript, please see the code below
<%# Page language="c#" AutoEventWireup="false" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>SessionRedirect</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<form method="post" name="frmRedirect" target="_blank">
<input type="hidden" name="email" value="<%=Session["Email"].ToString() %>" />
<input type="hidden" name="pass" value="<%= Session["PWD"].ToString() %>" />
<input type="hidden" name="User" value="<%= Session["User"].ToString() %>" />
</form>
<script type="text/javascript">
if(frmRedirect.User.value == "P")
{
frmRedirect.action = "http://cmsstag/partnerzone/index.aspx";
}
else
frmRedirect.action = "http://cmsstag/studentportal/index.aspx";
document.frmRedirect.submit();
location.replace("index.aspx");
</script>
<%
Session.Remove("registration");
Session.Remove("User");
Session.Remove("UserId");
Session.Remove("UserLoggedIn");
Session.Remove("AgentCode");
Session.Abandon();
%>
</body>
</html>
Now I want to open page in new window with size given by me when I use "frmRedirect.action" used in above code.
This is a rather complicated example.
What you could try is:
open a new window first with javascript window.open() and set its dimensions and name
submit the form to it setting the correct target name as you've set it in window.open()
I've tried it. It works.
Edit
This is the code for you. Maybe you will have to set some time between opening a new window and submitting a form to make sure the window is already created (use setTimeout).
// open a new window with proper size
window.open("", "MySubWindow", "height=480,width=640");
// do your action assignments
frmRedirect.target = "MySubWindow";
frmRedirect.submit();
location.replace("index.aspx");