taking play framework object in a javascript variable - javascript

I have a map declared in template parameters with the following syntax
#(formData : scala.collection.Map[String, scala.List[String]], previousData : scala.collection.Map[String,String], resultList: scala.List[String])(implicit flash: play.api.mvc.Flash)
I want to read the previousData map object and want to store it in a javascript variable.
I actually want to set the value in a textbox by fetching the value from the map object. I know that I can use document.getElementById in javascript to set the value of a particular textbox. Could anyone please help? If some other way is possible please let me know.
I tried the following method but it isn't working.
function loadPreviousData()
{
if(#previousData != null)
{
var x = #{previousData.getOrElse("name",null)};
alert("Name is " +x);
}
}

Yes you can use JQuery which is widely used nowadays. Let's say txtname is the id of your textbox then you can do like this
$("#txtname").val(x);
Here x is the variable in which you extracts the data.

I haven't found a way to directly solve this, but there's a method which worked for me and so I'm sharing.
I used a Json object instead of a Map to tackle this. The required data in the key value format was filled in JSON object and passed that JSON object in the form of a String using toString() method.
Ok(views.html.serviceReplay.render(formData, resultList.toList, fetchFormDataInJson.toString,newFlash))
In the view section, this Json object was obtained as a string.
#(formData : scala.collection.Map[String, scala.List[String]], resultList: scala.List[String], previousPageData : String)(implicit flash: play.api.mvc.Flash)
And finally, in order to obtain in a variable at the view section, following instruction was used.
var previousDataInJson = JSON.parse('#previousPageData'.replace(/"/g, '"'));
This worked for me. Hope it helps others.
Additionally, if we want to do via Map object I found a solution to that as well.
I was unable to directly use #formData directly in the javascript code, but it worked in the HTML section, therefore I used in the following scenario.
<select name="service" id="service">
<option value="">Select Service</option>
#for(serviceName <- formData.getOrElse("service",null)) {
<option value="#serviceName">#serviceName</option>
}
</select>
Now the value has been assigned to the serviceName, therefore, this can be easily retrieved using JQuery using the following syntax.
var service = $("#service").val();

Related

How to copy the value of a yform to an other field

In our (hybris) shop some products have a yform to summarize the parts of the product. Is there an easy way to copy the value of the sum field into an other field (automaticly) like the productquantity (no yForm)?
I guess I need javascript, but the id of the sumfield is generatad, so I don't know how to get the sum. Also my Javascript abilities are quite limited...
UPDATE:
To get the value I use this part of code:
copyYFormValueToProductQuantity : function() {
var copyText = document.querySelector('input[id*="sum"]').value
if (copyText > 0 && copyText != null)
{
//do stuff
}
console.log("Copied value: " + copyText)
},
But this line
document.querySelector('input[id*="sum"]').value
returns null. If I use it in the browserconsole, it also returns null. But after I inspected the element it works and returns the value I want to. So I guess I am missing some JS-basics here and the object isn't ready before?
Btw.: I call this function with a keydown-eventlistener.
This can most likely be done from the jsp files. There you have all the data that is needed, so you most likely need to only copy that field where you need it.
We can also help you more if you add some code examples here (what exactly is that yform?). If you struggle to find where in code is that specific yform created/added, it's always worth giving a try to search for the applied classes of the html (search the entire project and see what you find).
As I understand your question, you are saying that you want to copy the value of a yForm field named sum into a non-yForm field named productquantity, and you are asking specifically about how to access the value of a yForm field from JavaScript. If I understand this correctly, you can do so by calling the following JavaScript API:
ORBEON.xforms.Document.getValue("sum");
You can find more about this and other related API on Client-side JavaScript API.

Pass object to html String

I am in a situation here, i think its a simple one but i can't sort it out.
I Have a HTML element where i should pass a json Object
code
var x = "<li id='tag_1'></li>"
var obj = {"name":"krishna","id":"krish1"}
when I convert this to html i want to get Like this
<li id="tag_1" data-options={obj}></li>
I tried $(x).data("options",{obj}),
tried to pass as a string when creating the html element,but did'nt work
Thanks
$(x).data("options",{obj}) is a perfectly good way to do it, provided you fix the syntax error. Just pass obj directly, and jQuery will save it as an object. It will not, however, be added as an attribute.
$(x).data("options",obj)
If you look at the documentation for .data() it specifies that your value doesn't have to be a string:
value
Type: Anything
The new data value; this can be any Javascript type except undefined.
Try $(x).attr("data-options",JSON.stringify(obj))
If you don't want it printed in your HTML use $(x).data("options",obj)

How do I access an object property dynamically using a variable in JavaScript?

I’m trying to filter data from JSON in JavaScript.
I define a variable a. I want the property of whatever value a is equal to (not item.a). So far I’ve been unable to find a way of doing it.
Everything else is working correctly because when I changed it to a specific entry (item.date for example) it works fine. I cannot figure out the correct syntax.
while(i< elements.length){
var a=elements[i].id;
if(elements[i].name == 'targetfeild'){
$(elements[i]).val($.map(result,function(item){var test = elements[i].id;return item.a;}));
}
i++;
}
Try item[a], javascript objects can also be accessed this way.

Access to model object by EL in javascript function?

Here is my markup, I am using jtsl core tag
<c:forEach var="attr" items="${attributes}">
<c:when test='${attr.controlType == "textField"}'>
<script>createTextField("${attr}");</script>
</c:when>
</c:forEach>
So the "attributes" is a list of objects which resides in the model.
I want to call the createTextField function and I want access to the "attr"
in that function.
Here is my function, but I can't get access to the object, says it is undefined.
function createTextField(object) {
document.write(object.name);
}
Any ideas? would be appreciated.
This is not going to work. Java and JavaScript doesn't run in the same environment. You're basically passing attr.toString() to the JavaScript function which look by default like com.example.ClassName#hashcode. The JavaScript String object doesn't have a name property.
There are basically two ways to get it to work:
You need to convert the Java object as represented by #{attr} to a string which conforms the JavaScript object notation (also known as JSON). E.g.
<script>createTextField(${attr.asJson});</script>
with something like (with little help of Gson):
public String getAsJson() {
return new Gson().toJson(this);
}
You can of course also manually build it using StringBuilder or something. JSON format isn't that hard.
Pass only the property/properties of interest as long as they can be represented as String. E.g.
<script>createTextField("${attr.name}");</script>
with
function createTextField(name) {
document.write(name);
}

store return json value in input hidden field

I was wondering if it's possible to store the return json in a hidden input field. For example this is what my json return:
[{"id":"15aea3fa","firstname":"John","lastname":"Doe"}]
I would like to just store the id in a hidden field so I can reference it later to do something with it.
Example: I have something like this:
<input id="HiddenForId" type="hidden" value="" />
and would like jquery to return the value later to me like so:
var scheduletimeid = $('#HiddenForId').val();
Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...
Here I'll explain what I mean:
<input type="hidden" value="{"name":"John"}">
As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:
<input type="hidden" value="{" rubbish >
So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:
> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"
Now that value can be safely stored in an input hidden type like so:
<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">
or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:
<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>
Now to read the data back we can do something like:
> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}
You can use input.value = JSON.stringify(obj) to transform the object to a string.And when you need it back you can use obj = JSON.parse(input.value)
The JSON object is available on modern browsers or you can use the json2.js library from json.org
You can store it in a hidden field, OR store it in a javascript object (my preference) as the likely access will be via javascript.
NOTE: since you have an array, this would then be accessed as myvariable[0] for the first element (as you have it).
EDIT show example:
clip...
success: function(msg)
{
LoadProviders(msg);
},
...
var myvariable ="";
function LoadProviders(jdata)
{
myvariable = jdata;
};
alert(myvariable[0].id);// shows "15aea3fa" in the alert
EDIT: Created this page:http://jsfiddle.net/GNyQn/ to demonstrate the above. This example makes the assumption that you have already properly returned your named string values in the array and simply need to store it per OP question. In the example, I also put the values of the first array returned (per OP example) into a div as text.
I am not sure why this has been viewed as "complex" as I see no simpler way to handle these strings in this array.
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).
Anyway, if that is an array wrapper, you'll want something like this:
$('#my-hidden-field').val(theObject[0].id);
You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,
$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;
This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.
just set the hidden field with javascript :
document.getElementById('elementId').value = 'whatever';
or do I miss something?
base64 solution
// encode
theInput.value = btoa(JSON.stringify({ test: true }));
// decode
let decoded = JSON.parse(atob(theInput.value));
Why base64?
The input field may be processed by a backend that runs in a different programming language than JavaScript. For instance, in PHP, rawurlencode implementation is slightly different from JavaScript encodeURIComponent. By encoding it in base64, you are sure that whatever other programming language runs on the backend, it will process it as expected.

Categories

Resources