Struts object accessing in JS - javascript

I have a bean and want to iterate through the values and store it in an array.
My form bean name is keywords and the element to be accessed is keywordList, so in my JS when I alert("${keywords.keywordList}");
I get [com.test.bean.Keyword#10, com.test.bean.Keyword#f, com.test.bean.Keyword#e], but I want the values and assign them to a var, how can I do this?

javascript and java are two different languages, you can not assume that you pass the keywords.keywordList in java and get the corresponding objects in javascript, you need to iterate the keywordlist in java and create the corresponding javascript objects manually.
update: some pseudocode
out.print("var keywordsInJS = []")
for (String keyword : keywordList) {
out.print("var keyword = '" + keyword + "';");
out.print("keywordsInJS.push(keyword);");
}
// now you can use keywordsInJS in js.

Here is how I solved my problem
<script>
var i = 0;
var collection = new Array();
</script>
And since I was using logic:iterator and displaying the values in the table, I added
<script>
collection[i++] = "${keyword.name}";
</script>
Now when I alert collection, all the words are in the array. Which is exactly what I need.

This is what I have done to solve this issue on JSP page
< %# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
var keyWordsArray=new Array();
var rowCounter=0;
<c:forEach items="${keywords.keywordList}" var="keyWords">
var fieldObj=new Object();
fieldObj.value='<c:out value="${keyWords}"/>'
keyWordsArray[rowCounter]=fieldObj;
rowCounter++;
</c:forEach>
</script>
</code>
Now you can access keWordArray in Javascript.

In my experience JS and Java doesn't interact well...
I suggest you to use HTML as a middle term for them to interact. Like, for example, displaying the contents of the list in invisible text in html (with iterator and the property indexed you can have different names for each text), then you can get them in JS.
You should also keep the length of the list so when you iterate in JS you know when to stop.
I know this far from a perfect solution and far from something remotely nice to do. But I know no better way to do it :(
Hope there is one, so I can also use it :)

Related

passing variable values from c# to javascript

First of all, sorry for bringing a question that has been answered so many times, but I have tried most of the procedures mentioned and still can't get it working.
I have an ASP.NET app (server-side), and I would like to visualize some results by using WebGL (JavaScript, client-side). I am able to create the canvas in aspx file and to draw a 3D object (a cube) by writing ALL the necessary JS code in a jscript file (As long as I know what I want to draw in advance, and writing all that in Jscript). However, my intention is to write a different object depending on my server-side code. When I click a visualize button, a postback is triggered. In the server some code is executed, and some coordinates are returned in an array, defined global in the aspx.cs file. I would need to pass that array of node coordinates from the server to the JS file in order to draw actually the object I want.
Here is basically what I have tried:
The easiest way I have found to pass a variable is to declare a property public in aspx.cs (c# code) and then in JS writing:
var clientVariable = '<%=ServerVariable%>';
I have tried this not with an array, but just with a string variable and if writing:
alert(clientVariable);
I see "<%=ServerVariable%>" in the window, NOT the actual value. I don´t know if I need any additional library or what. If I can't even get this easy example working, I don't know how I would even do it with a double array. I´m using MCVS08, ASP.NET 3.5 with HTML5.
Apart from that, I have tried to convert the array not with JSON, but with:
Page.ClientScript.RegisterArrayDeclaration();
I've used ClientScript.RegisterStartupScript(GetType(), "alert", "test2('" + A + "');", true);
I've tried to use a hidden block to store the session value, etc.
So basically, summing Up, I would like to have:
server-side: after executing a function of the code behind in the server, when rendering the page again I will have a global variable in aspx.cs which is a double[,] coordinates, containing the coordinates of nodes that will define the 3D object.
aspx: in html (not asp.net) I have a canvas tag in which I intend to have the visualization. The script that will render the image client-side is stored in a JScript file. In this file, inside a function I have a variable var vertices = []; which I need to feed with the values I got from the server in coordinates array. I don't know how to achieve this the best way. Would you recommend to use AJAX?
Any suggestion/comment would be very appreciated. As the dummy example with a simple string is not working (forgetting about canvas, webGL and all that stuff), may I need anything else or am I misunderstanding how to do it properly?
When I need to pass variables into JavaScript I usually I prefer var clientVariable = '<%=ServerVariable%>'; solution. This method is sufficient for small number of scalar variables. If you need to pass a complex object or a array, consider to use JavaScriptSerizlizer.
The behavior you are having it might happen for number of reasons. One of them might occur, if you have included a scriptlet into .js file, and not into .aspx file.
Here is how I would do this:
webgl-draw-file.js:
window.WebGlDraw = function(points /* point array */)
{
// Draw points here
}
Page1.aspx.cs:
public string GetSerializedServerVariable()
{
new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ServerVariable);
}
Page1.aspx:
<html>
<header>
<script src="webgl-draw-file.js"/>
<script type=text/javascript>
window.WebGlDraw(<%=this.GetSerializedServerVariable()%>);
</script>
</header>
<body>
...
</body>
</html>
To understand a better what values are passed to the JS function, take a look at a page source using your browser. You should see a JSON representation of your array instead of <%=Page.GetSerializedServerVariable()%> scriptlet.
It should look something like this:
<html>
<header>
<script src="webgl-draw-file.js"/>
<script type=text/javascript>
window.WebGlDraw([{x:1, y:2}, {x:1, y:2}, {x:1, y:2}, {x:1, y:2}]);
</script>
</header>
<body>
...
</body>
</html>
can u serialize the data like this:
<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var doublearr = <%= serializer.Serialize(ServerVariable) %>;

Javascript : how to get value from a Script Tag

I am trying to get the following value from the script below
Use this field to store the Account to which the Opportunity is related
<script>sfdcPage.setHelp('Opportunity.Account', 'Use this field to store the Account to which the Opportunity is related');</script>
i can get to this script tag by using :
document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1];
Can you please let me know.
Many thanks.
I would not recommend putting script tags within your tables, etc. In other words, I wouldn't mix script tags with other content-related HTML like that. If you want to store little bits of info like that in your HTML for the purpose of JS, I'd use data attributes instead.
The simple answer to your question though is to just use the innerHTML or innerText property as follows:
document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1].innerHTML;
Use innerHtml as
document.getElementsByTagName('tbody')[6].
getElementsByTagName('script')[1].
innerHtml;
OR
Set an id to get script content as below example
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
console.log($('script'));
</script>
fiddle
There are lots of ways to do this. One solution....
var scrs = document.getElementsByTagName('script');
var newscr = "";
for (var i=0; i<scrs.length; i++) {
newscr = scrs[i].innerHtml.replace('sfdcPage.setHelp(', 'myfunction(');
if (newscr != scrs[i].innerHtml) {
eval(newscr);
}
}
(although parsing / rewriting the javascript is an ugly hack - if it's your code then your reading then you should know what you put in there).

How to access Dictionary Generic object in javascript which passed from server side

I want to access Dictionary Generic object(pass from asp.net server side) In javascript...
& i also want to retrieve that dictionary as key ,value pair ..
Please help me to solve this issue. Thanks in Advance.
If you're using MVC this can be easily achieved with:
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
// go ahead and use the model javascript variable to bind with ko
</script>
You just have to pass the to a view that contains that bits of code
Its bit easy, Try to use below code.
<script type="text/javascript">
var perm =#Html.Raw(Json.Encode(#ViewBag.Message));
</script>

javascript, how to take value from an input by class?

I use this code to get value from an input box:
var suggest_type = document.getElementById('ac-type').value;
Now I need to apply my js code on several other pages. I heard that it's not nice to repeat an ID on one website. So, I'm thinking to change to use class like this:
var suggest_type = document.getElementByClass('ac-type').value;
This doesn't get the value. How can I use class to get value?
You should stick with using ID's - they only have to be unique within a page.
If you must use classes, you need to use getElementsByClassName():
var elems = document.getElementsByClassName('ac-type');
var value = elems[0].value;
However this function is not well supported on older browsers, which is another good reason to stick with IDs.
Its absolutely fine to repeat ids across a website just not on a single html document.
ID's should be unique within one html page.
It's actually :
var suggest_type = document.getElementsByClassName('ac-type')[0].value;
But I agree with Jon Taylor, ID's can be the same within a website, as long they are not duplicated on the same page.
try using this:
var elements = document.getElementsByClassName('ac-type'); // this is an array containing all matched elements
Use jquery just by using -
$('.ac-type').val();
you will get value.

Get User control id within user control at runtime

is it possible to get the ID assigned to User Control from the control using javascript or jquery.
Thanks
What ASP.NET normally does is prefix your control's ID with a string that it uses to determine where in ASP.NET's control tree your actual control resides.
With that in mind, what I normally do is to use jQuery's 'ends with' selector to get the full ASP.NET-parsed ID at runtime.
Something like:
// get a handle on your original control
var myControl = $('[id$="<myOriginalId>"]');
// and then access it's properties
var myRuntimeId = myControl.eq(0).attr('id');
As you can most probably imagine, that's not going to cut it when you've got UserControls with the same ID used in different places of the form. I just jump in and put in some tweaks here and there (probably with using the .eq() function) to suit my business need.
You could put a class on the usercontrol, and then use something like $(".myUC").attr("id")
This might help you to look at it from a different point of view:
In .Net you can get the generated ID by using myControl.ClientID.
If you put that in a javascript variable - I know it's not neat - you can then easily fetch it.
<!--mypage.aspx-->
<script>
var myIdVar = "<%=myControl.ClientID%>";
if(myIdVar == "foo")
{
alert("bar");
}
</script>

Categories