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.
Related
So I started to learn HTML and JavaScript not long ago and I wonder how I could access an URL/download a file from a function I made with JavaScript in another file and imported it with
<script src="jscriptSheet.js"></script>
Maybe I am wording the search badly but I didn't found anything that helps me. The only thing I saw, was doing a form and sending it to a server, but that's not what I need (I think).
What I'm doing is creating 2 dates that need to be passed to the URL so it can access the file and download it:
<div class="dateWrapper">
<p id="date1">Date1:</p>
<input id="date1INPUT" type="date">
<p id="date2">Date2:</p>
<input id="date2INPUT" type="date">
<br><br>
<button id="datesubmit" type="submit" onclick="downloadF()">Download file.</button>
</div>
And the function made with JavaScript:
function downloadF{
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
}
When I execute this, it downloads nothing, it's just a normal button with no action.
How can I do it?
You do not want type=submit if you want to do something else than submitting. INSTEAD use a button as below or attach to the submit handler of the form and use preventDefault if you do not want to submit
I use location= you can use window.open(url) too but that may be blocked
Also your function should be
function functionname() { ... }
Anyway here is an example
document.getElementById("datesubmit").addEventListener("click",function {
location="100.100.100.100/something/something.php"+
"?date1="+document.getElementById("date1INPUT").value+
"&date2="+document.getElementById("date2INPUT").value
})
<div class="dateWrapper">
<p id="date1">Date1:</p>
<input id="date1INPUT" type="date">
<p id="date2">Date2:</p>
<input id="date2INPUT" type="date">
<br><br>
<button id="datesubmit" type="button">Download file.</button>
</div>
If you set the header in the PHP you will see a download dialog
header("Content-type: application/octet-stream");
Welcome to stackoverflow!
As already mentioned in a comment, you don't want to have the type set to "submit" when the button should not really submit the inputs but call a custom javascript function. Instead you just want to have the type set to "button".
Moreover you should define your javascript function like this (watch out for the parentheses):
function downloadF(){
// Access your input fields here
}
For accessing DOM elements you might want to have a look here at w3schools
function downloadF{
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
}
this is having invalid syntax. The JavaScript function should be defined like ( Very basically),
var f1 = function(){
}
function f2(){
}
And,
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
Here you are inserting something like date1 & data2 But it's not exist in your function. You can't use undefined variables.
And if you skip all syntax errors and look at the command
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
you are just setting a variable href and you didn't do any actions.
First learn basic javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript
And the answer of your question is,
If the target file is directly downloadable, you can use window.open('the_target_url') inside function.
If not,
You should do something in PHP. Please refer this link Download file from PHP
In VB, I am working on an MVC project. I have a text box to enter some search criteria, and a button next to it that upon pressing will submit the value of the text box. Html Snippet:
<input type="text" id="mySearchField" />
<button onclick="location.href='#Url.Action("Search", "Movies", New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'">Search</button>
My question revolves around the final part:
New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'"
The code above does not work or compile, but this is my general idea of what I am attemping to do.
I want to pass the value of the text box along into the Movies/Search function, however I am at a loss as to how to format the line to mix the html, asp, and javascript all at once.
My VB Function for clarity:
Function Search(searchCriteria As String) As ActionResult
Return View()
End Function
Any advice is much appreciated!
This should be pretty close. This has jQuery as a prerequisite. To make this maintainable (you can do this, or not), I'd use NewtonSoft.Json to serialize the URL to Javascript properly, and url-encode the text box value.
<input type="text" id="mySearchField" />
<button id=myButton>Search</button>
<script>
var url = '#Html.Raw(Url.Action("Search", "Movies"))';
$("#myButton").click(function(){
location.href = url + '?searchCriteria=' + $("#mySearchField").val()
});
</script>
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
Ok, so I'm REALLY new to programming and javascript, but I'm having a problem with this little string of code. The thing that is bothering me about it, is that I have done things similar to this in other programs, but it's just not working right in this specific little part of this program. Here is basically what isn't working:
<html>
<script type="text/javascript">
function test()
{
var myTextField = document.getElementById('myText');
document.write (myTextField);
}
</script>
<form>
<input type="text" id="myText">
<input type="submit" value="submit" OnClick="test()">
</form>
</html>
When I do this, it returns [object HTMLInputElement] instead of the value of that text field. Thanks for any help cause I'm most of you know this. :P
getElementById returns the Object itself, which has many methods and properties as members.
You need to reference the value property, like this:
document.getElementById('myText').value;
That should work :)
Also, here's a general reference: https://developer.mozilla.org/en/A_re-introduction_to_JavaScript
Try:
document.write (myTextField.value);
function test()
{
var myTextField = document.getElementById('myText').value;
alert(myTextField);
// or
console.log(myTextField);
}
You should not use document.write here, as you document is already loaded. Document.write will remove the page.
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