Reference a variable in the s:url action attribute - javascript

So I have a variable set in the page scope like:
<s:set name="targetAction" var="targetAction" value="%{'someActionName'}" />
I want to use this "targetAction" variable in the action attribute of the <s:url> tag. Is this possible?
I tried this way:
<s:url action="%{#targetAction}" />
but the action attribute is not evaluated and it is set to "%{#targetAction}" instead of the value specified in <s:set> tag by someActionName variable.
Any suggestions?
EDIT:
Corrected the typo with double quotes.
EDIT2:
Well, I'm using struts 2.1.3 if that matters at all. Anyway, I intend to use this url in a javascript variable like this:
var targetAction = '<s:property value="%{#targetAction}" />';
var actionURL = '<s:url action="<my dynamic action name specified by the targetAction variable needs to be here>" />
Is there anyway to let it know that value mentioned for the action attribute is a javascript variable and not a string as such? I mean how do I escape javascript content in this scenario?

Yes this is possible. The name attribute of <s:set> tag is deprecated use var instead.
BTW this variable a not set in page scope because you are not using scope="page" and default is action scope.
And you have typo in action attribute.
<s:set var="targetAction" value="%{'someActionName'}" />
<s:url action="%{#targetAction}" />
Javascript:
var targetAction = '<s:property value="%{#targetAction}" />';
var actionURL = '<s:url action="%{#targetAction}" />';

You have probably don't use alTSyntax in the tags. Try to set it to true in struts.properties.
### use alternative syntax that requires %{} in most places
### to evaluate expressions for String attributes for tags
struts.tag.altSyntax=true

In Struts 2.3 worked
<c:set var="businessActionMapping" value="foo" scope="session"/>
<s:form action="%{#session.businessActionMapping}"
You might have need to set altSyntax=TRUE in struts.properties

Related

Why the disabled button is not getting enabled using the jquery? [duplicate]

I'm trying make some stuff in jQuery using ASP.NET. But the ID from runat="server" is not the same as the id used in HTML.
I used to use this to get the ID from this situation:
$("#<%=txtTest.ClientID%>").val();
But in this case, it does not work. I'm clueless as to why.
Javascript
/* Modal */
function contatoModal() {
//alert("Test");
alert($("#<%=txtTest.ClientID%>").val());
}
HTML
< input runat="server" id="txtTest" value="test" />
Any tips?
<%= txtTest.ClientID %> should work but not in a separate javascript file where server side scripts do not execute. Another possibility is to use a class selector:
<input runat="server" id="txtTest" value="test" class="txtTest" />
and then:
var value = $('.txtTest').val();
In WebForm / HTML Page....
<asp:TextBox ID="txtUserName" runat="server" Class="form-control"></asp:TextBox>
In Jquery
var UserName = $("[id*=txtUserName]").val();
alert(UserName);
100% Sure its Working for me....
As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.
<input runat="server" id="txtText" />
When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):
<input id="ctl00_contentplaceholder_txtText" />
To find this control:
$("input[id$='txtText']")
Take caution when using this within a repeater.
Try putting it into a variable name:
var txtTestID = '#' + '<%=txtTest.ClientID %>';
$(txtTestID).val();
I'm not sure if the <%= likes being inside double quotes. I've always had mixed behaviors when not using the single quote.
When using ASP.NET 4 and the ClientIDMode is set to “Predictable”, you can predict the ID based on hierarchy. Or set it set to “Static”, so asp.net wont mess it up.
ScottGu's article on it http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx
And this is extremely useful when using external JS file scenarios.
As Darin Dimitrov said in his answer:
<%= txtTest.ClientID %> should work but not in a separate javascript
file where server side scripts do not execute.
The solutions that I could find for those are:
<input runat="server" id="txtTest" value="test" class="txtTest" />
Use class instead of ID
Using class you can retrieve the value anywhere. This is one of the best solutions (usually the best)
var value = $('.txtTest').val();
Use ClientID code in the aspx
You can always call ClientID in the aspx, but if you are working with some kind of structure, this isn't the best solution. I like to use this method when I'm testing something.
var value = $('#<%=txtTest.ClientID%>').val();
You can also use ClientID in a external js file with a workaround. IT'S NOT PRETTY, use only if you really need it. I usually do this when I use Telerik.
In the aspx:
var id = <%=txtTest.ClientID%>;
In the js file:
var value = $('#'+id).val();
Use Control.ClientIDMode Property Static
so the HTML becomes
<input runat="server" id="txtTest" value="test" ClientIDMode="Static" />
and the js can call it as it is named of
var value = $('#txtTest').val();
The problem with this solution is that you need to be very careful to avoid duplicity on the ids of your page. Try never use Static mode in a controller.
As states MSDN:
The ClientID value is set to the value of the ID property. If the
control is a naming container, the control is used as the top of the
hierarchy of naming containers for any controls that it contains.
The link of shaans's answer is a awesome place to check extra information about ClientIDMode.
Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)
To avoid issues with rendered ID's, use a class instead. This won't change during rendering:
function contatoModal() {
//alert("Test");
alert($(".txtTest").val());
}
HTML:
< input runat="server" id="txtTest" value="test" class="txtText" />
Adding a css class to the input and then using this class in jQuery to getting the input element will solve the issue.

How to pass a JavaScript variable to DIV tag?

I am trying a code to pass a javascript variable to the div tag to change its attribute. If anyone knows how to do this, help me.
<div id="rate" class="money" data-wpac-chan=""></div>
I want to pass a javascript variable to the data-wpac-chan.
<script type="text/javascript">
var div = document.getElementById("rate").data-wpac-chan = "bal";
</script>
It is not working.
I want to replace data-wpac-chan=" " to data-wpac-chan="bal"
This should do it:
document.getElementById("rate").setAttribute("data-wpac-chan", "bal");
SetAtrribute will set any attribute on an HTML element.
You can also use dataset to assign the value to the attributes that has data-. Notice that, you need to use the camelcase as attribute name. So, wpac-chan becomes wpacChan
document.getElementById("rate").dataset.wpacChan = 'bal'
<div id="rate" class="money" data-wpac-chan="">sadasd</div>

struts2 property value as argument of javascript function

I have one in jsp page.
i want to pass this value as argument of java script function call
my jsp apge code is:
<input type="submit" onclick="play(<s:property value="vname"/>)">
my java script function code:
function play(n)
{
alert(n);
}
please help me to solve this problem;
regard
Rohit kachhadiya
You have to wrap struts tags with quotes:
<input type="submit" onclick="play('<s:property value="vname"/>')">
otherwise the value of "vname" will be interpreted as a JavaScript variable, not a string!
Using struts2 tag:
<s:submit onclick="javascript:play('%{vname}')" />
Agree with daveoncode, apart from that
In your js, get it directly like
var varName = document.forms[0].name/id.value;
Or you have one more option to write inline js and pass value of your element. But its a bad practice.

How can I know the id of a JSF component so I can use in Javascript

Problem: Sometimes you will want to access a component from javascript with
getElementById, but id's are generated dynamically in JSF, so you
need a method of getting an objects id. I answer below on how you can do this.
Original Question:
I want to use some code like below. How can I reference the inputText JSF component in my Javascript?
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>Input Name Page</title>
<script type="javascript" >
function myFunc() {
// how can I get the contents of the inputText component below
alert("Your email address is: " + document.getElementById("emailAddress").value);
}
</script>
</head>
<h:body>
<f:view>
<h:form>
Please enter your email address:<br/>
<h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>
</h:form>
</f:view>
</h:body>
</html>
Update: this post Client Identifiers in JSF2.0 discusses using a technique like:
<script type="javascript" >
function myFunc() {
alert("Your email address is: " + document.getElementById("#{myInptTxtId.clientId}").value);
}
</script>
<h:inputText id="myInptTxtId" value="backingBean.emailAddress"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>
Suggesting that the attribute id on the inputText component
creates an object that can be accessed with EL using #{myInptTxtId},
in the above example. The article goes on to state that JSF 2.0 adds
the zero-argument getClientId() method to the UIComponent class.
Thereby allowing the #{myInptTxtId.clientId} construct suggested
above to get the actual generated id of the component.
Though in my tests this doesn't work. Can anyone else confirm/deny.
The answers suggested below suffer from drawback that the above
technique doesn't. So it would be good to know if the above technique
actually works.
You need to use exactly the ID as JSF has assigned in the generated HTML output. Rightclick the page in your webbrowser and choose View Source. That's exactly the HTML code which JS sees (you know, JS runs in webbrowser and intercepts on HTML DOM tree).
Given a
<h:form>
<h:inputText id="emailAddresses" ... />
It'll look something like this:
<form id="j_id0">
<input type="text" id="j_id0:emailAddress" ... />
Where j_id0 is the generated ID of the generated HTML <form> element.
You'd rather give all JSF NamingContainer components a fixed id so that JSF don't autogenerate them. The <h:form> is one of them.
<h:form id="formId">
<h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/>
This way the form won't get an autogenerated ID like j_id0 and the input field will get a fixed ID of formId:emailAddress. You can then just reference it as such in JS.
var input = document.getElementById('formId:emailAddress');
From that point on you can continue using JS code as usual. E.g. getting value via input.value.
See also:
How to select JSF components using jQuery?
Update as per your update: you misunderstood the blog article. The special #{component} reference refers to the current component where the EL expression is been evaluated and this works only inside any of the attributes of the component itself. Whatever you want can also be achieved as follows:
var input = document.getElementById('#{emailAddress.clientId}');
with (note the binding to the view, you should absolutely not bind it to a bean)
<h:inputText binding="#{emailAddress}" />
but that's plain ugly. Better use the following approach wherein you pass the generated HTML DOM element as JavaScript this reference to the function
<h:inputText onclick="show(this)" />
with
function show(input) {
alert(input.value);
}
If you're using jQuery, you can even go a step further by abstracting them using a style class as marker interface
<h:inputText styleClass="someMarkerClass" />
with
$(document).on("click", ".someMarkerClass", function() {
var $input = $(this);
alert($input.val());
});
Answer: So this is the technique I'm happiest with. Doesn't require doing too much weird stuff to figure out the id of a component. Remember the whole point of this is so you can know the id of a component from anywhere on your page, not just from the actual component itself. This is key. I press a button, launch javascript function, and it should be able to access any other component, not just the one that launched it.
This solution doesn't require any 'right-click' and see what the id is. That type of solution is brittle, as the id is dynamically generated and if I change the page I'll have to go through that nonsense each time.
Bind the component to a backing bean.
Reference the bound component wherever you want.
So here is a sample of how that can be done.
Assumptions: I have an *.xhtml page (could be *.jsp) and I have defined a backing bean. I'm also using JSF 2.0.
*.xhtml page
<script>
function myFunc() {
var inputText = document.getElementById("#{backBean.emailAddyInputText.clientId}")
alert("The email address is: " + inputText.value );
}
</script>
<h:inputText binding="#{backBean.emailAddyInputText}"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>
BackBean.java
UIInput emailAddyInputText;
Make sure to create your getter/setter for this property too.
Id is dynamically generated, so you should define names for all parent elements to avoid j_id123-like ids.
Note that if you use jQuery to select element - than you should use double slash before colon:
jQuery("my-form-id\\:my-text-input-block\\:my-input-id")
instead of:
jQuery("my-form-id:my-text-input-block:my-input-id")
In case of Richfaces you can use el expression on jsf page:
#{rich:element('native-jsf-input-id')}
to select javascript element, for example:
#{rich:element('native-jsf-input-id')}.value = "Enter something here";
You can view the HTML source when this is generated and see what the id is set to, so you can use that in your JavaScript. As it's in a form it is probably prepending the form id to it.
I know this is not the JSF way but if you want to avoid the ID pain you can set a special CSS class for the selector. Just make sure to use a good name so that when someone reads the class name it is clear that it was used for this purpose.
<h:inputText id="emailAddresses" class="emailAddressesForSelector"...
In your JavaScript:
jQuery('.emailAddressesForSelector');
Of course you would still have to manually manage class name uniqueness.
I do think this is maintainable as long as you do not use this in reusable components. In that case you could generate the class names using a convention.
<h:form id="myform">
<h:inputText id="name" value="#{beanClass.name}"
a:placeholder="Enter Client Title"> </h:inputText>
</h:form>
This is a small example of jsf. Now I will write javascript code to get the value of the above jsf component:
var x = document.getElementById('myform:name').value; //here x will be of string type
var y= parseInt(x,10); //here we converted x into Integer type and can do the
//arithmetic operations as well

Getting ID from asp.net runat server in jQuery

I'm trying make some stuff in jQuery using ASP.NET. But the ID from runat="server" is not the same as the id used in HTML.
I used to use this to get the ID from this situation:
$("#<%=txtTest.ClientID%>").val();
But in this case, it does not work. I'm clueless as to why.
Javascript
/* Modal */
function contatoModal() {
//alert("Test");
alert($("#<%=txtTest.ClientID%>").val());
}
HTML
< input runat="server" id="txtTest" value="test" />
Any tips?
<%= txtTest.ClientID %> should work but not in a separate javascript file where server side scripts do not execute. Another possibility is to use a class selector:
<input runat="server" id="txtTest" value="test" class="txtTest" />
and then:
var value = $('.txtTest').val();
In WebForm / HTML Page....
<asp:TextBox ID="txtUserName" runat="server" Class="form-control"></asp:TextBox>
In Jquery
var UserName = $("[id*=txtUserName]").val();
alert(UserName);
100% Sure its Working for me....
As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.
<input runat="server" id="txtText" />
When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):
<input id="ctl00_contentplaceholder_txtText" />
To find this control:
$("input[id$='txtText']")
Take caution when using this within a repeater.
Try putting it into a variable name:
var txtTestID = '#' + '<%=txtTest.ClientID %>';
$(txtTestID).val();
I'm not sure if the <%= likes being inside double quotes. I've always had mixed behaviors when not using the single quote.
When using ASP.NET 4 and the ClientIDMode is set to “Predictable”, you can predict the ID based on hierarchy. Or set it set to “Static”, so asp.net wont mess it up.
ScottGu's article on it http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx
And this is extremely useful when using external JS file scenarios.
As Darin Dimitrov said in his answer:
<%= txtTest.ClientID %> should work but not in a separate javascript
file where server side scripts do not execute.
The solutions that I could find for those are:
<input runat="server" id="txtTest" value="test" class="txtTest" />
Use class instead of ID
Using class you can retrieve the value anywhere. This is one of the best solutions (usually the best)
var value = $('.txtTest').val();
Use ClientID code in the aspx
You can always call ClientID in the aspx, but if you are working with some kind of structure, this isn't the best solution. I like to use this method when I'm testing something.
var value = $('#<%=txtTest.ClientID%>').val();
You can also use ClientID in a external js file with a workaround. IT'S NOT PRETTY, use only if you really need it. I usually do this when I use Telerik.
In the aspx:
var id = <%=txtTest.ClientID%>;
In the js file:
var value = $('#'+id).val();
Use Control.ClientIDMode Property Static
so the HTML becomes
<input runat="server" id="txtTest" value="test" ClientIDMode="Static" />
and the js can call it as it is named of
var value = $('#txtTest').val();
The problem with this solution is that you need to be very careful to avoid duplicity on the ids of your page. Try never use Static mode in a controller.
As states MSDN:
The ClientID value is set to the value of the ID property. If the
control is a naming container, the control is used as the top of the
hierarchy of naming containers for any controls that it contains.
The link of shaans's answer is a awesome place to check extra information about ClientIDMode.
Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)
To avoid issues with rendered ID's, use a class instead. This won't change during rendering:
function contatoModal() {
//alert("Test");
alert($(".txtTest").val());
}
HTML:
< input runat="server" id="txtTest" value="test" class="txtText" />
Adding a css class to the input and then using this class in jQuery to getting the input element will solve the issue.

Categories