JavaScript EJB variable field holding value? - java

I have an ajax enabled list of records that I'm going through and each one has a dropdown box that I'm trying to make a required field for the form to submit. To complicate matters the 'Close Record' button is not the submit button so I can't just use required attribute on the select(dropdown box) that I'm using. The value for the selected dropdown box is saved in an Enterprise Java Bean so I thought I could just write a JavaScript function to check the value:
function CheckForm() {
var clearObj = document.getElementById("mySelect");
if(clearObj.value != "") {
return true;
} else {
clearObj.style.backgroundColor ='yellow';
}
return false;
}
This doesn't work because once I close one and go to the next it's maintaining the value of the previous record on the page. Basically I have an update-content event that I need to know how to handle. Any ideas as to how to manipulate the DOM or JSON object to make this select a required field? Thanks.

With the little information given, I would assume that when you close the existing record and then loading the next record, you are doing it through an ajax request. If thats the case, then you can add a call back for the ajax request, which would reset the drop down.
This should be a comment, but as you see, I dont have 50 points :-)

Related

Selenium made a sendKeys for two fields instead of one for some reason

I made a pretty simple selenium test, where I want to open web page, clear field value, start entering text for this field, select first value from the hint drop down.
Web site is aviasales.com (I just found some site with a lot of controls, this is not an advertisement)
I did
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).clear();
and it was working perfectly, I also checked via console that this is the only one object on a page like:
document.getElementById('flights-origin-prepop-whitelabel_en')
So, in next line I'm sending value:
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).sendKeys("LAX");
but it send LAX value for both "flights-origin-prepop-whitelabel_en" and "flights-destination-prepop-whitelabel_en" for some reason, then i tried
DriverFactory.getDriver().findElement(By.id("//input[#id='flights-destination-prepop-whitelabel_en'][#placeholder='Destination']")).sendKeys(destinationAirport);
but I got the same result:
What could be a reason and how to fix this?
Thank you!
Yep... there's some weird behavior going on there. The site is copying whatever is entered into the first field into the second for reason I don't understand. I gave up trying to understand it and found a way around it.
Whenever I write code that I know I'm going to reuse, I put them into functions. Here's the script code
driver.navigate().to(url);
setOrigin("LAX");
setDestination("DFW");
...and since you are likely to use these repeatedly, the support functions.
public static void setOrigin(String origin)
{
WebElement e = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(origin);
e.sendKeys(Keys.TAB);
}
public static void setDestination(String dest)
{
WebElement e = driver.findElement(By.id("flights-destination-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(dest);
e.sendKeys(Keys.TAB);
}
You can see the functions but basically I click in the field, clear the text (because usually there's something already in there), send the text, and then press to move out of the field and choose the default (first choice).
The reason of your issue is the ORIGIN and DESTINATION inputbox binded keyboard event which used to supply an autocomplete list according to your typed characters.
The binded keyborad event breaks the normal sendKeys() functionality. I met similar case in my projects and questions on StackOverFlow.
I tried input 'GSO' into DESTINATION by sendKeys('GSO'), but I get 'GGSSOO' on page after the sendKeys() complete.
To resolve your problem, we can't use sendKeys(), we have to use executeScript() to set the value by javascript in backgroud. But executeScript() won't fire keyborad event so you won't get the autocomplete list. So we need find out a way to fire keyborady event after set value by javascript.
Below code snippet worked on chrome when i tested on aviasales.com:
private void inputAirport(WebElement targetEle, String city) {
String script = "arguments[0].value = arguments[1]";
// set value by javascript in background
((JavascriptExecutor) driver).executeScript(script, targetEle, city + "6");
// wait 1s
Thread.sleep(1000);
// press backspace key to delete the last character to fire keyborad event
targetEle.sendKeys(Keys.BACK_SPACE);
// wait 2s to wait autocomplete list pop-up
Thread.sleep(2000);
// choose the first item of autocomplete list
driver.findElement(By.cssSelector("ul.mewtwo-autocomplete-list > li:nth-child(1)")).click();
}
public void inputOrigin(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
return inputAirport(target, city);
}
public void inputDestination(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepopflights-destination-prepop-whitelabel_en"));
return inputAirport(target, city);
}

how to forward back to JSP page without losing the data entered in fields?

I have a simple MVC-based JSP application. Something like:
*.jsp -> ControllerServlet -> *Command.java -> *Service.java -> *DAO.java -> Oracle db
A typical link in the application looks like this:
myapp/controller?cmd=ShowEditUser&userid=55
Which causes ShowEditUserCommand.java execute() method to run and will forward to editUser.jsp
In editUser.jsp, they fill in the fields, then click Save which posts to myapp/controller?cmd=ModifyUser which runs ModifyUserCommand.java execute() method which modifies the user data and forwards to viewUser.jsp.
Everything works fine.
The problem is, in ModifyUserCommand.execute() I'm checking to see if the username is unique. If they try to enter a username that already exists, I set an error value to true and errorMessage value to Already in use.
Then because of the error I forward to the original editUser.jsp (not viewUser.jsp) and the error is displayed above the form.
MY PROBLEM IS (finally! ;) -- when the user is returned to editUser.jsp with the error message displayed, the data they entered in the fields is all blanked out. How can I set it so whatever they entered in the fields is still in place?
Any suggestions or advice are greatly appreciated!
Rob
Simplest way would be to pass the form fields back to your editUser.jsp in your forward action in ModifyUserCommand.execute(). You can do that with individual parameters i.e.
editUser.jsp?field1=1&field2=2
Alternatively, you could pass data with other methods - i.e. encoded JSON.
You can then process your fields in your editUser.jsp via the page's request object and set your form field values accordingly.
There may be other ways to do this depending on what underlying framework (if any) you are using. But this is a basic way of approaching it.

ASP.NET Page.ispostback equivalent in JSP/Java

Is there any ASP.NET Page.IsPostback equivalent in JSP/Java? What I need to do is check whether this request is first time or is it result of post back. There are few Combo Boxes on JSP page and I need to load it only for the first time, (I am loading combo box's data from DB) not everytime page reloads. We reload the same page based on various input/selections etc. So I was looking for that type of method.
if ( "POST".equalsIgnoreCase(request.getMethod()) &&
((request.getRemoteURL() != null &&
request.getRemoteURL().toString().equalsIgnoreCase("http://yoursite.com")) {
//postback call
}
You may also see this question

ajax call in jsf 2.0 (myfaces), the onevent Javascript function in the ajax tag gets called before the rendering is complete

This is my first time asking a question on a forum, since usually my questions have already been asked and answered. I haven't found an answer to this problem that works for me, so here goes:
I'm making an Ajax call in JSF 2.0 like this:
< f :ajax listener="#{myReferenceController.clearRequiredReferenceNumber}"
onevent="resetFocus" execute="#form"
render=":resultsForm:ResultsDisplay" />
Everything in the listener works perfectly, and the data is then rendered as expected in the data table that I have in my .xhtml page. The problem is that the Javascript that I call in the onevent seems to be getting called before the rendering is complete, and therefore the process of resetting the focus to a column in my datatable doesn't work, since the datatable is removed and then re-added to the DOM when the Ajax is finished re-rendering.
I'm looking in my Javascript for the status of "success", in hopes that at this point, the rendering would have completed. Alas, this is not the case, and my getElementById (actually dojo.byId) is not finding the element in the datatable. I know my Javascript function works under normal circumstances, since I'm calling this same function in a situation where there is not an Ajax call, and everything works perfectly there.
If I could just avoid rendering the cell in the table that I'm trying to set focus to, that would be great, but my listener is making changes to this cell in the ajax call. I'm at my wits end, so any ideas on this would be very appreciated.
-- in response to Balusc (heard good things about you, btw)
Hmm, I was actually on the right track I think, but still seem to be having troubles. I am checking for "success" and still even in success, am not able to set the focus here.
Here's my Javascript function that is checking for "success": This function works in another situation, where it's not attached to an Ajax event.
function resetFocus(data) {
var theRow = dojo.byId("resultsForm:selectedRow").value;
if (data.status == "success") {
dojo.query('[widgetId]',dojo.byId('theResultsDataTable'))
.forEach(function(node) {
var widget = dijit.byNode(node);
var theId = widget.attr("id")
if (theId.indexOf(':' + theRow + ':') != -1) {
if (theId.indexOf('theOrppoNum') != -1) {
widget.focus();
widget.attr("isFocused",true);
}
}
});
}
}
The function attached to the onevent attribute will actually be invoked three times. One time before the ajax request is been sent, one time after the ajax response is been arrived and one time when the HTML DOM is successfully updated. You should be checking the status property of the given data argument for that.
function onEventFunction(data) {
var status = data.status; // Can be "begin", "complete" or "success".
switch (status) {
case "begin": // Before the ajax request is sent.
// ...
break;
case "complete": // After the ajax response is arrived.
// ...
break;
case "success": // After update of HTML DOM based on ajax response..
// ...
break;
}
}
In your particular case, you thus just need to add a check if the status is success.
function resetFocus(data) {
if (data.status == "success") {
// Do your job here.
}
}

how to change the value of textfield + jQuery + Struts2

I have two textfield A , B : i want to do something like when i enter something in textfield A,this value will be use it in some action and result will be displayed in textfield B without clicking the submit button using ajax.
how can i do it please ? note that i am a using struts2
Most of the information has already been provided by #alexanderb and i believe that Jquery is good way to go, now lets come to the second half of your question about using AJAX in your code. there are few ways you can send results from your action class.
Return JSON from your action class and use above code.
Use stream result type in your S2 code and place the data in the textfield.
Still i believe JSON with Jquery is good way to go which not only provides you the feasibility to easily extend functionality in future but also provide a clean way.Struts2 provides a plugin which can convert the data being send from your action class to JSON and all you will be left to parse the JSON data in your UI to fill the text-box.For details how to work with JSON in s2 refer to JSON plugin for detail
S2-json-plugin
With JSON plugin your flow will be
Call your Action class on specific event in text box.
Configure your action to return JSON data using S2-JSon plugin.
Action will return JSON to the Jquery code.
Parse the JSON data and fill the text box with the value
It should be easy. Suppose you have action that takes value as string and return some string back, availble on '/app/service' url.
You can create such code for that:
$(function() {
$('#text_1').on('keyup', function() {
var value = $(this).val();
$.post('/app/service', JSON.stringify(value), function (r) {
$('text_1').text(r);
});
});
});

Categories