How to add selenium test coverage for jquery autocompleter text field - java

I have a text field , and jquery auto completer is binded to it.
html
<div id="autoCompleter">
<input type="text" name="symbol" />
</div>
javascript
$('#autoCompleter').delegate("input", "focus", AutoCompleter);
var AutoCompleter = function(event) {
$(this).autocomplete({
source: function(request, response) {
jQuery.extAjax({
url: url,
data: data,
success: response
});
},
select: function(event, ui) {
if (ui.item.value.match(/^Enter more characters...$/)) {
return false;
}
},
focus: function(event, ui) {
if (ui.item.value.match(/^Enter more characters...$/)) {
return false;
}
},
minLength: 2
});
$(this).autocomplete("search", $(this).val());
};
I have tried in the following way
#Test
public void autoCompleter() {
driver.findElementByName("symbol").sendKeys("22");
common.patientlyFindElement(By.xpath("//ul[contains(#class, 'ui-autocomplete')]//a[contains(.,'Enter more characters...')]")).click();
assertEquals(driver.findElementByName("symbol").getAttribute("value"), "22");
}

Related

Make a pie chart with tymeleaf highcharts spring mvc java

I want to create a pie chart with a dynamic data in highcharts
i really need your help
i wanna make a pie chart that counts the gender
here is my code
im really stuck there
..........................................................................
Controller :
#RequestMapping("/piechart")
public ResponseEntity<?> getAll(Model model) {
List<user> list = userRepository.allusers();
return new ResponseEntity<>(list,HttpStatus.OK);
}
Repository :
#Query(value=" SELECT *,count(*) AS count_gender FROM user GROUP BY gender", nativeQuery = true)
List<User> allusers();
HTML:
<body>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script th:inline="javascript">
$.ajax({
url: 'piechart',
dataType:'json',
success: function(result){
var series=[];
var data= [];
for(var i=0;i<result.length;i++){
var object={};
object.name=result[i].gender;
object.y=result[i];
data.push(object);
}
var seriesObject={
name:'percentage',
colorByPoint: true,
data: data
}
series.push(seriesObject);
drewPiechart(series);
}
})
function drewPiechart(series){
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
},
tooltip: {
formatter: function(){
return 'y value: '+this.y+'<br/>is '+this.percentage+'% of total ('+this.total+')';
}
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: true
}
},
series: series
});
}
</script>
</body>
</html>
here is my result:
it shows nothing bcz i didnt know how to get the count result of the query on the yaxis

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'
});
}
}
});
});
});

Code inserting into database twice

I have the form
<aui:form action="<%= editURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="name" />
<aui:input name="url" />
<aui:input name="address" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button name="cancel" value="Cancel"/>
</aui:button-row>
</aui:form>
and this piece of javascript code which is inserting into database twice I don't know why.
<aui:script use="aui-base,aui-form-validator,aui-io-request">
AUI().use('aui-base','aui-form-validator',function(A){
var rules = {
<portlet:namespace/>name: {
required: true
},
<portlet:namespace/>url: {
url: true
},
<portlet:namespace/>address: {
required: true
},
};
var fieldStrings = {
<portlet:namespace/>name: {
required: 'The Name field is required.'
},
<portlet:namespace/>address: {
required: 'The Address field is required.'
},
};
alert("validator");
new A.FormValidator({
boundingBox: '#<portlet:namespace/>fm',
fieldStrings: fieldStrings,
rules: rules,
showAllMessages:true,
on: {
validateField: function(event) {
},
validField: function(event) {
},
errorField: function(event) {
},
submitError: function(event) {
alert("submitError");
event.preventDefault(); //prevent form submit
},
submit: function(event) {
alert("Submit");
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
alert("inside success");// not getting this alert.
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
}
}
});
});
</aui:script>
However if I add the following piece of code, which is redundant because it is already present inside the submit block of above code and is not triggered any way because I do not have any save button in the form, then the value is inserted only once.
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
This code generates Uncaught TypeError: Cannot read property 'on' of null which I think is because there is no save button in the form. But adding this code, the value is inserted into database just once which is what I want but the logic is flawed. How can I get the results I want by just by using the first piece of code?
The insertion was happening twice. Once from the default form submit and other from the A.io.request. Adding this piece of code
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
resulted in the insertion only once. This code has obviously no relevance because there is no save button in the form. Hence there was Uncaught TypeError: Cannot read property 'on' of null which masked the flaw and prevented the form from being submitted twice.
Removing the above piece of code and preventing the default submit (by adding onSubmit="event.preventDefault(); in the form tag) resolves the issue.

How to check if form was submitted in Java

I have a form in jsp:
<form id="emailForm" data-role="form">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter full name..">
<input type="submit" id="emailSubmit" name="emailSubmit" class="btn btn-default" value="submit">
</form>
I send the form to controller using AJAX:
$("#emailSubmit").click(function(e){
e.preventDefault(); //STOP default action
var postData = $("#emailForm").serializeArray();
$.ajax(
{
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I check if it has been submitted in Controller here:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String emailSubmit = request.getParameter("emailSubmit");
if(emailSubmit != null){
// continue
}}
Can someone please tell me why when it checks if form was submitted in the controller that it is null?
For forms the standard way is to catch the submit event instead of the click event of the button:
$("#emailForm").submit(function(e){
e.preventDefault();
var postData = $(this).serializeArray(); // or: $(this).serialize();
$.ajax({
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I have tried several methods to be able to check the submit button isn't null and can't solve that issue. For now I have set a hidden input field in the form like so:
<input type="hidden" name="form" value="contactForm">
In controller I check for the form:
String form = request.getParameter("form");
if(form.equals("contactForm")){
// continue
}
Doing this enables me to know which form has been posted to the controller.

jQuery to show/hide divs in a JSP page

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>

Categories