Custom error placement not working in Jqueryvalidation plugin - java

I am using jquery validation plugin for validating my form data ,I have a fileupload element and then a button ,which opens browsing window to select file, as default error message is displayed between fileuplad element and button,I want to display this error message after button. I have tried many syntax as other similar question available on StackOverflow but none of them worked for me.
My jsp code is:
<tr>
<td>Browse Query File:</td>
<td>
<span id="input_span" style="background-color: red">
<INPUT type="text" id="inputfilepath" name="inputfilepath" placeholder="Query File" autocomplete='off' class="text" readonly="true" onclick="hidehint();" style="margin-left: 10%">
<input type="file" name="upFile" id="upFile" class="file" onchange="return do_upload(this.value);"/>
<input type="button" value="Browse" class="content_button2" onclick="do_click();"/>
</span>
<span id="error_span"> </span>
</td>
</tr>
I want my error message to be displayed in span having id-"error_span" on after it.
I have tried suggested code as:
errorPlacement: function(label, element)
{
if(element.attr("name") === "inputfilepath")
{
alert("call");
error.appendTo($('#error_span'));
}
else
{
error.insertAfter(element);
}
},
I also tried:
error.appendTo(element.parent("span").next("span"));
But it did't work for me.

rules: {
//rule stuff
}
groups: {
fileUpload: "upFile upButton"
},
errorPlacement: {
function(error, element) {
if(element.attr("name") == "upFile") {
error.insertAfter("#upButton");
} else {
error.insertAfter(element);
}
}
Be sure and give your button the name "upButton" for this to work.
You are basically saying you want to group those elements, and the error placement says, in the event that there is a validation error on the upFile, you want that error message to display after the upButton element.

Related

How to set link in onClick method in thymeleaf?

When I do a project with jsp, I try to keep it simple. Now I wanted to do project in Thymeleaf. I wanted to show a confirm dialogue box before deleting. I did it. But while I click ok I get an error. I think I cannot set a link properly inside the onclick method.
Here is my html code:
<tr th:each="student,iterStat : ${studentList}">
<td th:text="${student.id}"></td>
<td th:text="${student.roll}"></td>
<td th:text="${student.firstName}"></td>
<td th:text="${student.lastName}"></td>
<td th:text="${student.age}"></td>
<td>
<!-- <a th:href="#{/deleteStudent/(id=${student.id})}">Delete</a> -->
<a href="#" onclick="confirmRemoveQuestion('#{/deleteStudent/(id=${student.id})}')">
Delete
</a>
</td>
<script>
function confirmRemoveQuestion(link) {
if (show_confirm()) {
window.location = link;
this.hide();
} else {
this.hide();
}
}
function show_confirm() {
return confirm("Are you sure you want to do this?");
}
</script>
</tr>
Here is my Controller:
#RequestMapping(value = "/deleteStudent", method = RequestMethod.GET)
public String deleteStudent(#RequestParam(name="id") int id) {
studentService.deleteStudent(id);
return "redirect:/getStudents";
}
Note: Without dialogue box I can delete an object easily. That code is in comment line.
At last i have fixed it. i have replaced the line
Delete
with
Delete
And i have deleted javascript code. Because it is no longer needed!

Selenium can't find element by id and xpath

I read already all the other questions about this topic, there are a lot. I tried some but I do not find error in the code.
I tried adding a timer too to wait for the page to load.
Below the html code and the java:
HTML:
<form id="myform" method="get" action="">
<input type="hidden" name="something1" id="something1.1" />
<input type="hidden" name="something2" value="" />
<table>
<tr>
<td><label>Name: </label></td>
<td><select name="name">
<option selected="selected" value="1000">FirstNameOnly</option>
</select></td>
</tr>
<tr>
<td><label>Direction: </label></td>
<td><select name="Direction">
<option selected="selected" value="">Choose One</option>
<option value="UP">UP</option>
</select></td>
</tr>
<tr>
<td colspan="2"><label>Time: </label></td>
</tr>
<tr>
<td><label>From: </label></td>
<td><input type="text" value="" name="from" id="id6"/>
</tr>
<tr>
<td><label>To: </label></td>
<td><input type="text" value="" name="to" id="id7"/>
</tr>
<tr>
<td><label>File type: </label></td>
<td><span id="id8">
<input name="fileType" type="radio" checked="checked" value="0" id="id8-0"/><label for="id8-0">Excel</label>
<input name="fileType" type="radio" value="1" id="id8-1"/><label for="id8-1">CSV</label>
</span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="p::submit" id="id9" value="Preview">
<input type="submit" name="download" id="ida" value="Download">
</td>
</tr>
</table>
</form>
JAVA:
public void HeadlessChromeStartDownload(){
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
if (ValidateOS.isWindows()){
options.setBinary("C:\\Users\\Juri\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe");
System.out.println("Windows system");
} else if (ValidateOS.isUnix()){
options.setBinary("/path/to/chrome/not/yet/added");
}
options.addArguments("--headless --disable-gpu");
ChromeDriver driver = new ChromeDriver(options);
driver.get("http://localhost/that-test-page.html");
//WebElement timer = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("id8-1")));
WebElement select1 = driver.findElementByName("FirstNameOnly");
Select field1 = new Select(select1);
field1.selectByIndex(1);
WebElement select2 = driver.findElementByName("Direction");
Select field2 = new Select(select2);
field2.selectByIndex(1);
driver.findElementByName("from").sendKeys("21/06/2017");
driver.findElementByName("to").sendKeys("22/06/2017");
/*File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("C:\\screen1.jpg"));
System.out.println("Screen saved");
} catch (IOException e) { System.out.println("Screen NOT saved"); }
*/
//driver.findElement(By.id("id8-1")).click();
driver.findElement(By.xpath("//form[1]/input[6]")).click();
//driver.findElementById("ida").click();
driver.quit();
}
It really does not matter if I use:
driver.findElement(By.id("id8-1")).click();
or
driver.findElementById("id8-1").click();
or
driver.findElement(By.xpath("//form[1]/input[6]")).click();
I can't get Selenium to click on that radio button.
And the same goes for the rest of the code, in fact I used findElementByName which obviously is not the best choice.
Thanks to anyone who knows what is wrong with this code!! (: (:
UPDATE1:
So, I can not explain what happened yesterday. The website I am trying to test was using id8-1 for that radio button. Today it is id3-1, and both the solution with: driver.findElement(By.cssSelector("input[value='1']")).click(); or mine: driver.findElement(By.id("id3-1")).click(); worked.
I'm astonished. It was clearly 8 yesterday.
Still, I do not know if using the cssSelector solution is the best, because I want to work with the IDs.
I upvoted all the answers because all are useful but I wish to use IDs so I'm using my code.. In case of updates by your side I will choose it the one (: (:
Thanks to all!!!
When driving IE with Selenium, I encountered a problem where driver.find_element_by_id("elem_id") can't find it but running javascript document.getElementById("elem_id") in IE's developer console can. In my case, I was extracting a value. So I worked it around by doing driver.execute_script('return document.getElementById("elem_id").outerText')
Try with the following:
driver.findElement(By.xpath("//input[#name='fileType' AND #id='id8-1']")).click();
Does selenium throws an error? When trying to click an element that no longer existis into DOM, you will see an error like 'Element is no longer attached
to the DOM'.
Better than to using wait, is to write a method that verifies if the element is available. Try the following one:
private void waitUntilElementExistsAndIsVisible(final By by) {
new FluentWait<WebDriver>(driver).withTimeout(DEFAULT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
.pollingEvery(DEFAULT_SLEEP_TIME_IN_SECONDS, TimeUnit.SECONDS).ignoring(NoSuchElementException.class)
.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wd) {
return wd.findElement(by).isDisplayed();
}
});
}
Use it before executing some action with an element:
waitUntilElementExistsAndIsVisible(By.id("id8-1"));
driver.findElement(By.id("id8-1")).click();
Another workaround is to use the Action methods. Try to move the mouse to the enclosing tag (<span id="id8">), and then, click the desired element:
Actions builder = new Actions(driver);
builder.moveToElement(driver.findElement(By.id("id8"))).perform();
waitUntilElementExistsAndIsVisible(By.id("id8-1"));
driver.findElement(By.id("id8-1")).click();
You can achieve this without using xpath also
driver.findElement(By.cssSelector("input[value='1 0r 0']")).click();
You can select either 0 or 1 which you want to select

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

How do I show error information in web form?

This question is related to this. But since I haven't solved that question yet, I want to restate my problem a bit. I'm using Java Jersey REST API as my backend web service. The client side is a simple web form HTML page. Basically what I want is: If the user submits a web form and there are some errors caused by database unique constraint violation, I want the user to see an error message showing along with the id field in the form such as "ID already exists!". The web form is a simple form.html:
<form action="/myapp/rest/customer/created" method="POST">
<table border="1">
<tr>
<td>Customer name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Customer ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>Customer DOB:</td>
<td><input type="text" name="dob"></td>
</tr>
</table>
<br/>
<input type="submit" value="Submit">
</form>
If there is an error occurred, how to pass the error information from Jersey API to the client-side? My server-side POST call associated with this form submission is as follows:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("created")
public Response createCustomer(#FormParam("id") int id,
#FormParam("name") String name, #FormParam("dob") Date dob)
throws ServletException, IOException {
URI uri = URI.create(uriInfo.getPath());
Response r;
r = Response.created(uri).build();
try {
dbController.create(id, name, dob); //This may throw exception.
} catch (DataAccessException ex) {
//To do: How to pass the error message to the client-side UI via e.g., Ajax?
}
return r;
}
First of all add this somewhere in your code. It will display the error message:
<span id="errorDiv" name="errorDiv" class="errorDiv" ></span>
Next, modify your form declaration as:
<form action="/myapp/rest/customer/created" method="POST" onsubmit="return checkForm()">
Before submitting the form it will call checkForm() function. if the function returns true then it will post the form. if not then it will prevent form from submission and display error message.
Assuming that you are submitting the form contents by using jQuery/AJAX calls. You can return a String(default value = 'success') from the server. In case there is an error change the specific string and return it and check the value client-side.
responseTxt is the value returned.
function checkForm(){
//get values from form
var name= $("#name").val();
var id= $("#id").val();
var dob= $("#dob").val();
$.post('DESTINATION',{name:name,id:id,dob:dob},function(responseTxt) {
//MAKE YOUR CHECK HERE. JUST AN EXAMPLE
if (responseTxt.substring(0,4)=='succ'){
//redirect to destination
return true;
}else{
//display error in errorDiv span
$('#errorDiv').html('<font color=red>Wrong username or password.</font>');
//prevents form to be submitted
return false;
}
});
}
Hope it helps

Calling a jsp/html page using ajax in play 2.0

Can anyone guide me how can i call a jsp/html page using ajax in play framework?
I want to open a lightbox on click of a button and want to load that with a page containing data from database.
Currently i have just displayed the message using ajax. Below is the method inApplication.java
public static Result index()
{
return ok(index.render("Your new application is ready."));
}
My index.scala.html is:
#(products: List[Products])
#import helper._
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<h1>#products.size() product(s)</h1>
<table border=1>
<tr>
<td>Product Name</td>
<td>Quantity</td>
<td>Price</td>
</tr>
#for(product <- products) {
<tr>
<td>
#product.productname
</td>
<td>
#product.quantity
</td>
<td>
#product.price
</td>
<td id="items">
<input type="button" value="Add Product" name="#routes.Application.user(product.product_id)" id="but"/>
</td>
</tr>
}
</table>
<div class="result1" style="border: 1px solid black; padding: 5px;">not sent yet...</div>
<script type="text/javascript">
jQuery("#items a").click(
function () {
$.get(jQuery(this).attr("href"), function (data) {
$('.result').html(data);
});
return false;
}
)
</script>
You are on the good way.
Create a new action which will return only the html you need in your div (and not the complete html page).
public static Result detail(Integer productId)
{
Product product = .... (productId);
return ok(productDetail.render(product));
}
// with the route of course
productDetail.scala.html
#(product: Product)
My product #product.product_id is beautiful !
....
You must also add a jquery plugin to display your lightbox (there are a thousand...)
Your JsCode will be something like that:
$("#items a").click(function () {
$("#result").load($(this).attr("href"), function() {
displayPopup(); // code this
});
});
(Or maybe a totally different code if the plugin natively handle ajax...)
In resume, there is a lot of work to do, and many ways to do it.
Just try !

Categories