JSF resource bundle params in javascript? - javascript

I have a command button that generates a confirm pop-up. The text of the confirm comes from a message bundle. Is it possible to pass parameters to the confirm?
This is what I am trying:
<h:commandButton value="#{tkmsg.addAccount}" action="#{ebfAccountControllerBean.specifyEbfAddAccount}"
onclick="return confirm('#{tkmsg.confirmAddAccount}');">
<f:param value="this account"/>
<f:param value="this email"/>
</h:commandButton>
But it doesn't work. I just get
Are you sure you want to add account {0} with email {1}?
Do parameters only work with OutputText or OutputFormat? Is there any other way to do this? My next step would be to replace "this account" with data from the form.

What you're doing indeed doesn't work that way. JSF has no way to relate the f:param tags to that EL expression. Just think about it, even a human would not be able to guess this ;)
You could render your message upfront into something accessible via EL, using e.g. Tomahawks buffer:
<t:buffer into="#{buffer['confirm']}">
<h:outputFormat value="#{tkmsg.confirmAddAccount}">
<f:param value="this account"/>
<f:param value="this email"/>
</h:outputFormat>
</t:buffer>
#{buffer} is simply a hasmap declared as managed bean with request scope. After this you can reference #{buffer['confirm']} in the javascript statement.

Arjan gave a good example. An alternative is to write a JS function for that yourself. Here's a basic kickoff example which extends the JS String prototype with a new format() function.
<script>
String.prototype.format = function() {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function() {
return args[arguments[1]];
});
}
</script>
Use it as follows:
onclick="return confirm('#{tkmsg.confirmAddAccount}'.format('this account', 'this email'));"

Related

Struts2: Autopopulating fields based on a dropdown value without JavaScript

I tried searching the site but could not find an answer to my question.
i am developing a java Struts2 web application.
There are 3 form fields on a jsp page as follows:
(Struts2 tags are being used)
<s:form action="action1">
other fields
......
<s:select name="test1" list="{'A','B','C'}"></s:select>
<s:textfield name="test2"></s:textfield>
<s:textfield name="test3"></s:textfield>
.....
other fields
<s:submit value="submit1"><s/submit>
</s:form>
when a value is selected in test1 field, test2 and test3
would needed to be populated from the database based on the
value selected in test1.
as per the process i need to implement, i need to do some calculations based on the input from jsp1(presented above), and present the result on jsp2 which has to have entirely different content from jsp1. My issue is limited to the data entry in jsp1.
what would be the best way of doing this without javascript?
assume that javascript is disabled in the browsers accessing
the application.
thanks,
EDIT
It seems that there's a bit of confusion here, let's try to make it clear:
There are basically three ways of triggering a communication with the server from the browser:
submit HTML
submit JS
AJAX submit
You may or may not care about giving support to users browsing with JavaScript disabled;
if you DO NOT care, then you can proceed as you wish;
if you DO care, then you have two ways in front of you:
make an unique version of the pages, that works both with and without JS (by using ONLY option "1", "submit HTML");
make the pages working in two possible ways, mutually exclusive: while processing the page, you detect if the user has javascript enabled: if yes, you go with JS (submit or AJAX), if not, you fallback to the non JS solution ( "submit HTML" ).
Both this two solutions works with and without JS, but the latter is generally preferred because you can set up a nice, good-looking, user's experience-oriented WebApp for the 99% of the users, by using JavaScript and eventually AJAX, and create a fallback solution for the 1% of the users that, even if the site won't be nice as in the JS version, and even if it won't have ALL the features of the JS version, it would still be usable, and the core functionalities will be available.
As I said in the comment above, there is no need for the fallback version of the WebApp to be as nice, as fast, as good in user experience as the JS version: it should simply... work.
For example, this JSP will work in both cases: it will do a JavaScript Submit after selecting an element from the Select if JS is enabled, and it will do a submit after pressing the Submit button if JS is disabled.
With JS disabled, onchange will be ignored and <noscript> processed.
With JS enabled, onchange will be processed and <noscript> ignored.
<s:form action="myAction">
<s:select onchange="javascript:document.forms[0].submit();"
name="test1" value="test1" list="{'A','B','C'}" />
<s:textfield name="test2" value="test2" />
<noscript>
<span>
Since you have JS disabled,
you need to manually press to the GO button,
but you still can make it work ;)
</span>
<s:submit value="go" />
</noscript>
</s:form>
in your Action
public class MyAction extends ActionSupport{
private String test1="";
private String test2;
/* Getters and Setters */
public String execute(){
if (test1.length()>0)
assignValues();
return SUCCESS;
}
private void assignValues(){
if (test1.equals("A")){
test2 = "A was chosen, do something";
} else if (test1.equals("B")){
test2 = "B was chosen, do something else";
} else if (test1.equals("C")){
test2 = "C was chosen, what's next?";
}
}
}
The other doubts you are expressing in comments suggest that you may want to step back for a moment and read some Struts2 tutorial, to be sure of gaining the maximum from the framework.
If you have other fields in the same Form that you don't want to be affected, just declare a variable in the Action (with the Getter and the Setter), for each one of them: they will be preserved in the reloaded page, because they will be sent (because they're in form) with the submit, they will be injected through the Setter, they will be read back through the Getter and injected in the new page by the matching with their name and the Action variable.
Otherwise you could use AJAX, but I'd start from this.
And no, you can't nest forms.
Thanks to Andrea Ligios, i have the below solution to my issue.
jsp1 was changed as below
<s:form action="action2">
other fields
......
<s:select name="test1" list="{'Select','A','B','C'}"
onchange="javascript:document.forms[0].submit();"></s:select>
<noscript><s:submit value="populate test2 and test3"></s:submit></noscript>
<s:textfield name="test2"></s:textfield>
<s:textfield name="test3"></s:textfield>
.....
other fields
<s:submit value="submit1" action="action1"><s/submit>
</s:form>
struts.xml has following mappings
.....
<action name="action2" class="MyAction" method="populate">
<result name="success">/jsp1.jsp</result>
</action>
<action name="action1" class="MyAction">
<result name="success">/jsp2.jsp</result>
</action>
.....
MyAction has following code
public class MyAction extends ActionSupport{
//all field declarations
//Getters and Setters
public String execute(){
//do processing for jsp2 based on values from jsp1
return SUCCESS;
}
public String populate(){
//populate test2 and test3 from database based on value of test1
return SUCCESS;
}
}

Incorrect Javascript Functions?

I am completely brand new to Javascript. In fact, I'm just an Objective-C programmer looking to implement just a little Javascript into one of my apps. So, the problem is for whatever reason when I call my first function, nothing happens there I don't get the alert. When I call my second function I only get the alert, the button isn't actually clicked.
Code:
function myFunction(username, password) {
alert("Data will be entered");
document.getElementById('ctl00_plnMain_txtLogin').value = username;
document.getElementById('ctl00_plnMain_txtPassword').value = password;
}
function click() {
alert("The button was clicked");
document.getElementById("ctl00_plnMain_Submit1").click();
}
I can seem to run just a regular alert fine, but nothing else??? Is there something wrong in my function?
If it helps, on the website here is the "username" box:
<input name="ctl00$plnMain$txtLogin" type="text" maxlength="50" id="ctl00_plnMain_txtLogin" tabindex="1">
"password" box:
<input name="ctl00$plnMain$txtPassword" type="password" maxlength="255" id="ctl00_plnMain_txtPassword" tabindex="2">
the button:
<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); " name="ctl00$plnMain$Submit1" type="submit" id="ctl00_plnMain_Submit1" tabindex="3" value="Log In" title="Log in">
-- EDIT
Also, I am starting the functions through my objective C code. I grab a js file, then I am able to use its functions on a webpage.
I would recommend using a DOM abstraction library like jQuery
jQuery provides an 'on' method, it's used to bind events to DOM elements:
$('#ctl00_plnMain_Submit1').on('click', function (event) {
alert("The button was clicked");
}
It also provides a nice abstraction for collecting input values:
var userName = $('#ctl00_plnMain_txtLogin').val();
You can also use it to set the value of an input:
$('#ctl00_plnMain_txtLogin').val('New Value for This Input');
Populating inputs with a function:
function populateInputs (username, password) {
$('#ctl00_plnMain_txtLogin').val(username);
$('#ctl00_plnMain_txtPassword').val(password);
}
I am guessing you want the click function to be called when the button is clicked
You need to specify that then
<input onclick="click()" ....

How do I conditionally display a Javascript alert() that blocks the page from submitting until the user clicks "OK"?

I have a commandButton like this:
<p:commandButton value="Save" actionListener="#{bean.checkDetails}" action="#{bean.save}" />
My checkDetails() method checks some fields on the page and if they are not filled in, uses RequestContext to trigger a Javascript alert() which I want to use to block bean.save from being called until the user clicks "OK". The RequestContext piece looks like this:
RequestContext context = RequestContext.getCurrentInstance();
context.execute("alert('Details are not Complete.')");
My problem is I am not seeing the alert() dialog and bean.save is being called regardless of the state of the checkDetails() method.
Am I going about this completely the wrong way? I have spent three hours on this so far and I am plain stuck. If I remove the action method, the alert() pops up just fine.
Please, any input would be greatly appreciated.
My checkDetails() method checks some fields on the page and if they are not filled in...
As BalusC said, this can very easily be solved by adding required="true" to those fields, no need to write Java for this.
If you want to mix this up with the 'old-scool' alert() you can use the validationFailed callback parameter:
<h:form>
<p:inputText required="true" />
<p:commandButton value="submit" oncomplete="handleValidation(xhr, status, args)" />
</h:form>
<script type="text/javascript">
function handleValidation(xhr, status, args)
{
if(args.validationFailed)
{
alert('Details are not Complete.');
}
}
</script>

Sending multiple parameters to javascript from a HTML form button

Ok so i have a form that has three input boxes, at the moment they're text, but they will be changed to password. When the submit button is pressed i want the for to send the form data to an Ajax script.
I have this working with just one parameter the button looks like this:
<input type="submit" name="submit" value="Submit"
onClick="return pass(this.form.oldPass.value;">
Now i've tried adding the 'this.form' part three times because thats how many parameters the function would take but it just doesn't seem to do anything:
<input type="submit" name="submit" value="Submit"
onClick="return pass(this.form.oldPass.value,
this.form.newPass.value,
this.form.newPassCheck);">
Is this the right way to go about passing form data to a script? is there another way around it or am i just doing something wrong here?
thanks for the help, if you need anymore code i'll add it.
try this one. (you need jquery to do this.)
<form>
old pass <input type="password" id="old_pass" />
new pass <input type="password" id="new_pass" />
new pass confirmation <input type="password" id="new_pass_confirm"/>
</form>
in your .js file , write this:
$(document).ready(function(){
var old_pass = $('#old_pass').val();
var new_pass = $('#new_pass').val();
var new_pass_confirm = $('#new_pass_confirm').val();
//then call your method with those vars as parameter
anyMethod(old_pass, new_pass, new_pass_confirm);
});
//this is your function
function anyMethod(old_pass, new_pass, new_pass_confirm)
{
//put your validation code or ajax call here...
}
Add id for each of your input boxes and you can get value in function, like:
function pass() {
var old = document.getElementById("yourOldPassId").value;
var new = document.getElementById("yourNewPassId").value;
var newConfirm = document.getElementById("yourNewConfirmPassId").value;
}
Did you mean something like this
Give the inputs some ids and get the data from there.
Something like:
<input type bla bla id="whateverId0" />
For each input.
The submit should have something like onclick="whateverFunction()"
The js should look like:
function whateverFunction()
{
val0 = document.getElementById('whateverId0');
// For all 3 values.
// Do whatever you want with them.
}
I believe that you should add an onSubmit listener to your form. There are good js frameworks out there like jquery which are easy to use. That way you can make a listener which runs a function when you submit your form. In that function you can extract the data to json for example and ajax it to your server.
info about jquery
jquery ajax
how to extract form data

Spring MVC - Set an actionURL parameter with Javascript

Is it possible to dynamically set a Spring MVC portlet:actionURL portlet:param using javascript? I have tried with the following code, but the id value always comes across as null to the controller. I have verified that setting the portlet:param manually passes the value correctly:
<portlet:param name="id" value="2" />
I have also verified the value in the javascript is being set correctly and is not null.
(Note: I've changed the variable names, etc. from the original code to simplify it and obfuscate it since it is my employer's code.)
JSP:
<portlet:actionURL var="modifyURL">
<portlet:param name="do" value="modify" />
<portlet:param name="id" value="${model.id}" />
</portlet:actionURL>
...
<form:form action="${modifyURL}" id="modifyForm" modelAttribute="model">
<form:hidden path="id" id="id" />
</form:form>
Javascript called when the update URL is clicked:
function update() {
document.forms[0]["id"].value = selectedId;
document.forms[0].submit();
}
Controller:
#RequestMapping(params = {"do=modify"})
public void modify(#ModelAttribute("model") Model model,
#RequestParam(value = "id", required=true) Long id,
ActionRequest request, ActionResponse response,
SessionStatus sessionStatus, ModelMap modelMap) {
....
A co-worker figured it out. It looks like you just have to add the parameter to the action within the javascript and not include it in the actionURL or form.
JSP:
<portlet:actionURL var="modifyURL">
<portlet:param name="do" value="modify" />
</portlet:actionURL>
...
<form:form action="${modifyURL}" id="modifyForm" modelAttribute="model" method="POST">
</form:form>
Javascript called when the update URL is clicked:
function update() {
$("modifyForm").action = '${modifyURL}&id='+selectedId;
$("modifyForm").submit();
}
I came across this almost 3 years later, still i found it easier to add a hidden form field and when the action is clicked than to set this value to the hidden field
something like
<input type="submit" id="btn_terminate_cmpn"
value="Terminar campaƱa" onclick="setAction('terminate');">
and the javascript code
function setAction(action){
$("#actionToDo").val(action);
}
The URL generated by the portlet tag is on the server side. Javascript doesn't see the portlet tag. It only sees the actual URL. What your coworker is suggesting would work but it's not a good approach. Here he's just adding the dynamic parameter as a query string parameter which makes it visible to all the portlets on your target portal page. A better solution is to keep a hidden element (text box or something) and set the dynamic value to this hidden element in your onSubmit Javascript hander function.

Categories

Resources