onChange does not work for DateTimePicker in Struts 2 - javascript

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"/>

Related

Jquery onchange event not triggering

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

Datepicker isn't working inside search popup

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" />

jQuery dynamic added class gets not applied

I've got a quite strange behaviour. I append a class at runtime but the class doesn't get applied (although it is there as I can see by debugging via firebug). Here is a fully (un-)functional example:
<html>
<head>
<link rel='stylesheet' href='./jQuery/css/superfish/superfish.css' type='text/css' />
<link rel='Stylesheet' href='./jQuery/css/smoothness/jquery-ui-1.8.16.custom.css' type='text/css' />
<script type='text/javascript' src='./jQuery/js/jquery-1.6.2.min.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery-ui-1.8.16.custom.min.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery.ui.datepicker-de.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery-ui-timepicker.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery-ui-timepicker-de.js'></script>
<script type='text/javascript'>
$(function () {
$('.DateTimePicker').datetimepicker({
stepMinute: 15
});
});
</script>
</head>
<body>
<script type='text/javascript'>
function testMe() {
$("[id$=Working]").addClass('DateTimePicker');
}
</script>
<input id="notWorking" type="text">
<input id="clickToTest" type="button" onclick="testMe()">
<input id="static" type="text" class="DateTimePicker">
</body>
</html>
I think the issue you're having is that the datetimepicker() is initialised to all elements with a class .dateTimePicker, but when you are dynamically adding a class to other elements the datetimepicker does not get initialised again for these elements. Here is a piece of code that i've seen used before to get around this problem.
$(document).ready(function(){
$('.DateTimePicker').on('click', function(){
$(this).datetimepicker({
stepMinute : 15
}).datetimepicker('show');
});
});
This means the datetimepicker is invoked straight after it is attached using .on(). more info here. This way the datetimepicker will be initialised on all elements which have the class .DateTimePicker even if they are added dynamically. Hope this helps.
UPDATE:
There's a few other ways i've seen this done if you do not like this method. One neat way of doing it is here.
Another way is to remove the class the datetimepicker adds to the element (so it knows which elements have datetimepickers initialised on them) and then rebinding the datetimepicker to your class again.
function testMe() {
$("[id$=Working]").addClass('DateTimePicker');
$('.DateTimePicker').removeClass('hasDatepicker').datetimepicker({ stepMinute: 15 });
}
When you click your <input type="submit" /> the class is being added and then a POST is being performed which reloads the page and the class should not be there on the fresh load.
Try changing it to <input type="button" /> and it should probably work.

Creating a modal window onload of a page for user feedback

I have to create a modal window to display a popup or a modal window to get the feedback from the user for our intranet. This window should have a checkbox which says "do not ask this question again".
I tried creating this window using jquery but I dont understand how to do it. I even tried to google it but not getting proper answers. Can anyone please help me with this.
I am new to jquery.I have seen many sites where they have created modal windows but they use php and I cant. Please help me with jquery, jsp or javascript code for this purpose.
A screenshot from the use case document is attached.
Any help is appreciated. Thanks in advance.
p.s. I am using websphere portal.
Sorry the image wasnt allowed..
The below mentioned code also doenst work. Plz help.
<html>
<head>
<%#page session="false" contentType="text/html" pageEncoding="ISO-8859-1" import="java.util.*,javax.portlet.*,com.ibm.accessitservicesfeedbackpopup.*" %>
<%# taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
<%#taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.1/portlet-client-model" prefix="portlet-client-model" %>
<portlet:defineObjects/>
<link rel="stylesheet" type="text/css" href="<%= renderRequest.getContextPath() %>/style.css"/>
<link rel="stylesheet" type="text/css" href="<%= renderRequest.getContextPath() %>/jqModal.css"/>
<script language="javascript" type="text/javascript" src="<%= renderRequest.getContextPath() %>/jqModal.js"></script>
<script language="javascript" type="text/javascript">
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'yes')
(typeof callback == 'string') ?
window.location.href = callback :
callback();
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: true, trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
confirm('About to visit: '+this.href+' !',this.href);
return false;
});
});
</script>
</head>
<body>
view (confirm)
<!-- Confirm Dialog -->
<div class="jqmWindow" id="confirm">
<div id="ex3b" class="jqmConfirmWindow">
<div class="jqmConfirmTitle clearfix">
<em>Close</em>
</div>
<div class="jqmConfirmContent">
<p class="jqmConfirmMsg"></p>
<p>Continue?</p>
</div>
<input type="submit" value="no" />
<input type="submit" value="yes" />
</div>
</div>
</body>
</html>
There is nice jQuery dialog you can use. Just download jQuery and jquery ui (both js and css) and include to your project. It works prefectlly.

Apply jQuery datepicker to multiple instances

I've got a jQuery date picker control that works fine for once instance, but I'm not sure how to get it to work for multiple instances.
<script type="text/javascript">
$(function() {
$('#my_date').datepicker();
});
</script>
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
<%=Html.TextBox("my_date")%> <br/>
<% Next%>
<% End Using%>
Without the For Each loop, it works fine, but if there's more than one item in the "MyRecords" collection, then only the first text box gets a date picker (which makes sense since it's tied to the ID). I tried assigning a class to the text box and specifying:
$('.my_class').datepicker();
but while that shows a date picker everywhere, they all update the first text box.
What is the right way to make this work?
html:
<input type="text" class="datepick" id="date_1" />
<input type="text" class="datepick" id="date_2" />
<input type="text" class="datepick" id="date_3" />
script:
$('.datepick').each(function(){
$(this).datepicker();
});
(pseudo coded up a bit to keep it simpler)
I just had the same problem.
The correct way to use date pick is $('.my_class').datepicker(); but you need to make sure you don't assign the same ID to multiple datepickers.
The obvious answer would be to generate different ids, a separate id for each text box, something like
[int i=0]
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
[i++]
<%=Html.TextBox("my_date[i]")%> <br/>
<% Next%>
<% End Using%>
I don't know ASP.net so I just added some general C-like syntax code within square brackets. Translating it to actual ASP.net code shouldn't be a problem.
Then, you have to find a way to generate as many
$('#my_date[i]').datepicker();
as items in your Model.MyRecords. Again, within square brackets is your counter, so your jQuery function would be something like:
<script type="text/javascript">
$(function() {
$('#my_date1').datepicker();
$('#my_date2').datepicker();
$('#my_date3').datepicker();
...
});
</script>
<html>
<head>
<!-- jQuery JS Includes -->
<script type="text/javascript" src="jquery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery/ui/ui.core.js"></script>
<script type="text/javascript" src="jquery/ui/ui.datepicker.js"></script>
<!-- jQuery CSS Includes -->
<link type="text/css" href="jquery/themes/base/ui.core.css" rel="stylesheet" />
<link type="text/css" href="jquery/themes/base/ui.datepicker.css" rel="stylesheet" />
<link type="text/css" href="jquery/themes/base/ui.theme.css" rel="stylesheet" />
<!-- Setup Datepicker -->
<script type="text/javascript"><!--
$(function() {
$('input').filter('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
showOn: 'button',
buttonImage: 'jquery/images/calendar.gif',
buttonImageOnly: true
});
});
--></script>
</head>
<body>
<!-- Each input field needs a unique id, but all need to be datepicker -->
<p>Date 1: <input id="one" class="datepicker" type="text" readonly="true"></p>
<p>Date 2: <input id="two" class="datepicker" type="text" readonly="true"></p>
<p>Date 3: <input id="three" class="datepicker" type="text" readonly="true"></p>
</body>
</html>
There is a simple solution.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/flexcroll.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript" src="../js/JScript.js"></script>
<title>calendar</title>
<script type="text/javascript">
$(function(){$('.dateTxt').datepicker(); });
</script>
</head>
<body>
<p>Date 1: <input id="one" class="dateTxt" type="text" ></p>
<p>Date 2: <input id="two" class="dateTxt" type="text" ></p>
<p>Date 3: <input id="three" class="dateTxt" type="text" ></p>
</body>
</html>
When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.
function convertTxtToDate() {
$('.dateTxt').each(function () {
if ($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker');
}
$(this).datepicker();
});
}
A little note to the SeanJA answer.
Interestingly, if you use KnockoutJS and jQuery together
the following inputs with different IDs, but with the same data-bind observable:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />
will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).
Use separate observables in your ViewModel to bind a separate datepicker to each input:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />
Initialization:
$('.datepick').each(function(){
$(this).datepicker();
});
The solution here is to have different IDs as many of you have stated. The problem still lies deeper in datepicker. Please correct me, but doesn't the datepicker have one wrapper ID - "ui-datepicker-div." This is seen on http://jqueryui.com/demos/datepicker/#option-showOptions in the theming.
Is there an option that can change this ID to be a class? I don't want to have to fork this script just for this one obvious fix!!
To change use of class instead of ID
<script type="text/javascript">
$(function() {
$('.my_date1').datepicker();
$('.my_date2').datepicker();
$('.my_date3').datepicker();
...
});
</script>
I had the same problem, but finally discovered that it was an issue with the way I was invoking the script from an ASP web user control. I was using ClientScript.RegisterStartupScript(), but forgot to give the script a unique key (the second argument). With both scripts being assigned the same key, only the first box was actually being converted into a datepicker. So I decided to append the textbox's ID to the key to make it unique:
Page.ClientScript.RegisterStartupScript(this.GetType(), "DPSetup" + DPTextbox.ClientID, dpScript);
I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js
// this.element.on('click', $.proxy(this.show, this));
In my case, I had not given my <input> elements any ID, and was using a class to apply the datepicker as in SeanJA's answer, but the datepicker was only being applied to the first one. I discovered that JQuery was automatically adding an ID and it was the same one in all of the elements, which explained why only the first was getting datepickered.

Categories

Resources