jQuery to show/hide divs in a JSP page - java

I have a slight problem with my jQuery and I can't quite figure out where my problems lies, so if anyone could give me a hand with it is greatly appreciated.
I am using a jQuery function that when my #add div gets clicked, a JavaBean is called which adds the current page to the session user and when the #remove div gets clicked, a similar process is carried out that removes the current page from the user.
My problems starts when I try to check with the collection whether the current page is already associated with the user and if so display the #remove div and otherwise display the #add div.
Below is my script:
<script>
$(document).ready(function() {
$("#viewshow-text").load(function(){
if(${userShowDetails}) { <%-- this var can either be true or false depending on whether the page is associated with the user or not --%>
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
}
});
$("#add").click(function() {
$.post("addshow", {
item : "${param.show}"
}, function(data, status) {
}, function() {
<%-- hide a div and display the other --%>
$this.find('#addshow').hide(),
$this.find('#removeshow').show();
});
});
$("#remove").click(function() {
$.post("removeshow", {
item : "${param.show}"
}, function(data, status) {
}, function() {
$this.find('#removeshow').hide(),
$this.find('#addshow').show();
});
});
});
</script>
My div elements in question are as follows:
<div class="viewshow-text">
<c:if test="${!empty USER}"> <%-- only display if a user is logged in --%>
<div id="addshow" class="viewshow-button viewshowAdd-button">
<a id="add" href="#">Add to calendar</a>
</div>
<div id="removeshow" class="viewshow-button viewshowRemove-button">
<a id="remove" href="#">Remove from calendar</a>
</div>
</c:if>
</div>
I have no issues with my JavaBean properties as I double checked and they are displaying the contents expected:
$(document).ready(function() {
$(if(false) {
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
});
When the page is not in the user list.

Here try this,
<script>
$(document).ready(function() {
if(${userShowDetails}) {
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
};
$("#add").click(function() {
$.post("addshow", {
item : "${param.show}"
}).done(function(data) {
$('#addshow').hide(),
$('#removeshow').show();
});
});
$("#remove").click(function() {
$.post("removeshow", {
item : "${param.show}"
}).done(function(data) {
$('#removeshow').hide(),
$('#addshow').show();
});
});
});
</script>

Related

Tapestry Page turning to next page : Click on the next page (if the table content on the next page is editable, tapestry will report an error)

Click on the next page (if the table content on the next page table element contains <input: type="text"> )
org.apache.tapestry5.ioc.internal.util.TapestryException: The
elementValue component must be enclosed by a Form component. [at
classpath:com/zte/easweb/pages/home/MyInvoice.tml, line 178] at
org.apache.tapestry5.internal.structure.ComponentPageElementImpl.invoke(ComponentPageElementImpl.java:948)
at
org.apache.tapestry5.internal.structure.ComponentPageElementImpl.access$400(ComponentPageElementImpl.java:49)
at
org.apache.tapestry5.internal.structure.ComponentPageElementImpl$AbstractPhase.callback(ComponentPageElementImpl.java:159)
at
org.apache.tapestry5.internal.structure.ComponentPageElementImpl$SetupRenderPhase.render(ComponentPageElementImpl.java:189)
MyInvoice.java
public class MyInvoice {
public Pagination<FbpInvoiceV> getFbpInvoiceList() {
try {
logger.info("....1");
fbpInvoiceList = bc4Boe.boe__queryMyInvoiceList(searchCondition, grid.getCurrentPage(),grid.getRowsPerPage());
} catch (Exception e) {
logger.error("....2", e);
}
return fbpInvoiceList;
}
public boolean canNotUpdateInvoice(Integer index) {
FbpInvoiceV invoice = fbpInvoiceList.getItems().get(index - 1);
String checkStatus = invoice.getCheckStatus();
String standardCheckStatus = invoice.getStandardCheckStatus();
if ("4".equals(checkStatus) || "4".equals(standardCheckStatus)) {
return true;
}
return false;
}
}
<html>
<head></head>
<body>
<t:form t:id="optForm" clientvalidation="false">
<div class="pannel1">
<t:grid.zgrid t:id="grid" source="fbpInvoiceList" row="row" lean="true" rowsperpage="10" include="no,invoiceNo" model="model">
<t:parameter name="invoiceNoCell">
<div align="center" style="display: inline-block; white-space: nowrap;">
<t:if t:test="${canNotUpdateInvoice(row.no)}">
${row.invoiceNo}
<p:else>
<t:textfield t:id="invoiceNo" name="invoiceNo" value="row.invoiceNo" />
</p:else>
</t:if>
</div>
</t:parameter>
</t:grid.zgrid>
</div>
</t:form>
</body>
</html>

How to execute the controller based on input to a pop-up or dialog from ajax

in the belwo code "code_2" I have a controller that applies http method DELETE, to remove a specific product based on the provided id.
in "code_1", I am trying to create ajax call that shows or present to the user a dialog or pop-up with YES and NO BEFORE the controller in code_2 is executed. in other words, when the client call
/product/remove/2
he should be presented with a popup or dialog with YES and No. When he clicks YES, then the controller in code_2 should be executed normally. If he click NO, nothing should happen..only the dialog or the pop-up disappears.
For the pop-up or the dialog, I did the following as shown below:
<body>
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go" onclick="return confirm('Are you sure you want to search Google?')"/>
</form>
</body>
i could not not find a form with YES and NO buttons...can you help me to correct it
I have implemneted the below code_1 and code_2.
please let me know if the code is correct or needs to be modified...i do not have access to server moreover, I am new to ajax and spring mvc technologies.
code_1:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax confirm delete prodcut</title>
<script
src="${pageContext.request.contextPath }/resources/js/jquery-1.6.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#confirmremoveform').click(function() {
var idx = $('#idx').val();
var ans = confirm("Are you sure you want to delete this Record?");
if (ans) {
$.ajax({
type: "DELETE",
url: "/product/remove/" + idx,
dataType : 'json',
contentType : 'application/json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#onsuccessfuldelete").text(data);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
</script>
</head>
<body>
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go" onclick="return confirm('Are you sure you want to search Google?')"/>
</form>
</body>
</html>
code_2
#Controller
#RequestMapping("/product/remove")
public class RemoveProductPageController {
public final static String sRemoveProductFromListAttributeName = "removeProductFromList";
public final static String CONTROLLER_URL = "/product/remove";
public final static String DO_REMOVE_HANDLER_METHOD_URL = CONTROLLER_URL + "/{idx}";
#Autowired
private ProductService productService;
#RequestMapping(value = "/{idx}",
method = RequestMethod.DELETE)
#ResponseBody
public ResponseEntity<String> doRemove(#Validated #Size(min = 0) #PathVariable(required = true) int idx,
Model model) {
Product productToBeRemove = productService.getProductFromListByIdx(idx);
if (productToBeRemove == null) {
return new ResponseEntity<String>("no product is avaialble at index:" + idx, HttpStatus.NOT_FOUND);
}
model.addAttribute(RemoveProductPageController.sRemoveProductFromListAttributeName, productToBeRemove);
productService.removeProdcutFromListBxIdx(idx);
return new ResponseEntity<String>("product removed from index: " + idx, HttpStatus.OK);
}
}
Try using SWAL(SweetAlert). It is a customizable replacement for javascript popups.
There are a lot of options you can choose from.
Example:
JSP,
On click of your delete button
$('#[idOfDeleteButton]').click(function (e) {
e.preventDefault();
swal({
title: 'Are you sure you want to delete this record',
type: 'warning',
showCancelButton: true
}).then(function () {
//execute once user confirms else nothing happens
var deleteLink = "[link to controller]?id="+[idTobeDeleted];
$.ajax({
url: deleteLink ,
contentType: "application/json",
type: 'GET',
success: function (res) {
//res is the string returned in the controller
if (res === "Success!") {
swal({
title: res,
text: "Delete Successful!",
type: 'success'
});
} else {
swal({
title: res,
text: "Deleting record Failed!",
type: 'error'
});
}
}
});
});
});

Displaying database valuees obtained through a RESTful webservice in a JSP pag

I am implementing a messanger using Jax-Rs. I have a client application which use the implemented API. within the database message_id,message,date, sender fields are stored. I need to display these values within a div of jsp page of the client application.
client.jsp
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
<script>
function onTechIdChange() {
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details)
{
dispatchEvent(event)
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
Through this code nothing is displayed in the div. But values are printed in the tomcat console which ensures that all the methods within API are working properly. Do you have any idea? Thank you in advance
UPDATE
I Updated the javascript code snippet. But nothing is displayed inside the <p> tag
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details.sender)
{
display(name);
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
This is the section with the <p>
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
If somebody knows a tutorial regarding this can you upload a link?
I think you are not calling the display function that add the values to the DOM.
for(name in details){
display(name)
}
Also I am not sure that your parser is correct
success : function(result) {
var details = result[0]; -- Extract the first value of response
var name;
for(name in details) --- should be an array as well
{
dispatchEvent(event) -- I think here you need to call print function
}
alert(details.sender); -- If details.sender have the details probably the
iteration should be for(name in details.sender)
},
Also I reconsider the use of $.ajax, probably use $.get is better and also, use jsp I dont think is needed use a simple html with a javascript.

UI Bootstrap (AngularJS) modal is not working

I have this practice project that I am working on, but I cant get my UI Boostratp modal working. Using example from the site https://github.com/angular-ui/bootstrap/tree/master/src/modal I have been trying to implement this feature but without success.
I believe that this is because of that I do not have the knowledge to integrate demo code to my MVC style project (I have separate app.js, controller, and service files), and this one file example is rather confusing to me.
My folder/file structure:
Now, I have tried various things, including making a separate controller, and separate view for modal content (that's why I have bookDetailes.html and bookDetailesConreoller.js files but they are currently out of order - not connected in app.js's stat provider and their code is under comment). This is where I am:
A have a list of basic book details retrieved from data base and printed out in book.html view via data-ng-repeat. In every repeat I have an Action button that is supposed to open modal for editing or deleting that entry.
Here is my book.html file where I have nested the demo markup code from UI Bootsratp site:
<h4 class="text-center"><strong>Book Collection</strong></h4>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Publisher</th>
<th>City of Publishing</th>
<th>Genre</th>
<th>Action
<th>
</tr>
</thead>
<tbody data-ng-init="init()">
<tr data-ng-repeat="book in books">
<td>{{book.id}}</td>
<td>{{book.image}}</td>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.yearOfPublishing}}</td>
<td>{{book.publisher}}</td>
<td>{{book.cityOfPublishing}}</td>
<td>{{book.genre}}</td>
<td><a class="btn btn-default" data-toggle="modal" data-ng-click="open()">Action</a></td>
</tr>
</tbody>
</table>
<div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
As you can see, this last part after table tag is supposed to be modal markup taht is called when Action button is pressed and command "open()" i passed to bookController.js via data-ng-click.
My bookControler.js:
collectionsApp.controller('bookController', function($scope, bookService,
$state) {
var books = [];
$scope.save = function() {
bookService.save($scope.book, onSaveDelete);
}
$scope._delete = function(id) {
for (book in books) {
if (book.id === id) {
bookService._delete(book, onSaveDelete);
}
}
}
$scope.edit = function(id) {
for (book in books) {
if (book.id === id) {
$scope.book;
}
}
}
$scope.init = function() {
bookService.list(onInit);
}
// <-- Beginning of the modal controller code I inserted (and adopted) from the example:
$scope.items = [ 'item1', 'item2', 'item3' ];
$scope.open = function(size) {
modalInstance = $modal.open({
templateUrl : 'myModalContent.html',
controller : ModalInstanceCtrl,
size : size,
resolve : {
items : function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
var ModalInstanceCtrl = function($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item : $scope.items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
// <-- Ending of the modal code I have inserted from the example.
onSaveDelete = function(response) {
if (response.data.status === 'success') {
$scope.init();
} else {
alert("DEBUG ALERT: SAVE/DELETE FAIL");
}
};
onInit = function(response) {
$scope.books = response.data;
books = response.data;
};
});
Now, like this, code is working in the seance that data-ng-repeat is working and I get list of database entries on page load. But when I click on the Action button i get this error message in the console:
But when I add $modal to may code like this:
collectionsApp.controller('bookController', function($scope, bookService,
$state, $modal) {
var books = [];
...
I get this error on page load:
Can someone help me understand and implement modals to my project? Thanks in advance... ;)
Add this,
angular.module('Urapp', ['ui.bootstrap']);

Receiving jQuery body changes in Wicket

I got a question here regarding Wicket and jQuery. I got a WebPage which is rendered and shown by Wicket. Within this page I got one "draggable" and one "droppable" component, in which the user should be able to move components. This is realized via jQuery. Additionally I got a "Save" button at the end of the WebPage, which should save the new values (if there are any), which means: the newly dropped items. But if I click on "Save" I don't see the newly dropped objects within Wicket, I still just see the objects which have been in the "droppable" area from the beginning on. Here some Code snippets:
HTML:
<div class="container">
<div id="user">
<h1 class="ui-widget-header">Benutzer</h1>
<div class="ui-widget-content" id="userList">
<input type="text" placeholder="Benutzername" id="userNameSearch" />
<ul class="list-group">
<li class="list-group-item" wicket:id="userList"><span
wicket:id="user" id="user"></span><span style="visibility: hidden;" wicket:id="userId" id="userId"></span></li>
</ul>
</div>
</div>
<div id="project">
<h1 class="ui-widget-header">Benutzer im Projekt</h1>
<div class="ui-widget-content" id="project">
<ul class="list-group">
<li class="placeholder list-group-item"><span>Benutzer
in dieses Feld ziehen.</span></li>
<li class="list-group-item" wicket:id="usersInProjectList"><span
wicket:id="userInProject"></span><span style="visibility: hidden;" wicket:id="userInProjectId"></span></li>
</ul>
</div>
</div>
<button id="save" wicket:id="save">Speichern</button>
</div>
<script>
$(function() {
$("#userList li").draggable({
appendTo : "body",
helper : "clone"
});
$("#project ul")
.droppable(
{
activeClass : "ui-state-default",
hoverClass : "ui-state-hover",
accept : ":not(.ui-sortable-helper)",
drop : function(event, ui) {
$(this).find(".placeholder").remove();
var userName = ui.draggable.find("#user").text();
var userId = ui.draggable.find("#userId").text();
$("<li class=\"list-group-item new-project-member\" wicket:id=\"usersInProjectList\"><span wicket:id=\"userInProject\">"+userName+"</span><span style=\"visibility:hidden;\" wicket:id=\"userInProjectId\">"+userId+"</span></li>")
.appendTo(this);
$(ui.draggable).remove();
}
}).sortable({
items : "li:not(.placeholder)",
sort : function() {
// gets added unintentionally by droppable interacting with sortable
// using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
$(this).removeClass("ui-state-default");
}
});
$('#userNameSearch')
.keyup(
function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#userList li').show();
} else {
$('#userList li')
.each(
function() {
var text = $(this)
.text()
.toLowerCase();
(text.indexOf(valThis) >= 0) ? $(
this).show()
: $(this)
.hide();
});
}
;
});
});
</script>
Java Code (Wicket):
ListView userListView = new ListView("userList", finalUserList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("user", user.getLastname()+", "+user.getFirstname()));
item.add(new Label("userId", user.getId()));
}
};
ListView usersInProjectListView = new ListView("usersInProjectList", usersInProjectList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("userInProject", user.getLastname()+", "+user.getFirstname()));
item.add(new Label("userInProjectId", user.getId()));
}
};
usersInProjectListView.setOutputMarkupId(true);
add(new AjaxLink<Void>("save")
{
#Override
public void onClick(AjaxRequestTarget target)
{
System.out.println(target.getPage().get("usersInProjectList"));
//window.close(target);
}
});
add(userListView);
add(usersInProjectListView);
You could somehow get the changes from the client to the server, for example using Ajax. You can fire a callback function that can be added via AbstractAjaxBehaviour (see detail here), or maybe switch to wicket-dnd

Categories