Pass object to html String - javascript

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)

Related

How to get element from HTML stored in variable

I am running an API to retrieve email from external system. I managed to get HTML code from the returned JSON and store it in a variable. Now, I would like to run some further operations on this HTML - for example get all elements with
[data-type="whatever"].
It would be easy in html document:
var x = document.querySelectorAll('[data-type="whatever"]');
However the HTML document I want to work with is stored in the variable so the code I write in API does not recognise it as a document. How can I do it? Any suggestions with vanilla JS?
You can try something like this.
let rawDoc = '<html><head><title>Working with elements</title></head><body><div id="div1">The text above has been created dynamically.</div></body></html>'
let doc = document.createElement('html');
doc.innerHTML = rawDoc;
let div1 = doc.querySelector('#div1');
console.log(div1)
What if you use innerHTML? or maybe I don't fully understand the question.
Since you are working without a document you have 2 options.
1. Use regex to get what you need (something like /<.+>.+ data-type="whatever".+<\/.+>/gi) should do (but for an exact match you may need to make something better).
2. Insert the html in a hidden part of the dom and select what you need from it (like in Zohir answer - he provided a good example).
I used following code with angular to store whole html content in a variable and pass it as argument to call API.
var htmlBody = $('<div/>').append($('#htmlBody').clone()).html();
This might work for you as i was working on sending email to pass invoice template so try this.

taking play framework object in a javascript variable

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();

jQuery single line code optmization for getting and setting for the same input element

I'm using PHPStorm and have the following js code
$('#id'.val($('#id'.attr('default'));
The idea is to reset the value of a input field to it's default which is set in default attribute of the input element.
Now the IDE is suggesting me to avoid duplicate selectors.
Though it is working I'm interested in finding out what is the best way to optimize this code line?
Not exactly what you asked for but more future proof using data and not an attribute. You could even store complex data or other information in there as well like "originalvalue" or "lastchangedvalue" etc.
Storing in an attribute is fine however I prefer to store things like this in the data of the element like:
<myelementtag id="myid" data-defaultvalue="defaultvalue" />
You then access it like:
$('#myid').data("defaultvalue");
For example:
var myElement = $('#myid');
myElement.value = myElement.data('defaultvalue');
Want to reset the default?
var mynewdefault = "mynewvalue";
myElement.data('defaultvalue', mynewdefault);
Since you asked only one selector and one line code, please use like this as stated in jQuery documentation (middle section):
$("#id").val(function(index,value) {
return $(this).attr('default');
});
or if you want to avoid $(this):
$("#id").val(function (index, value) {
return this.getAttribute('default');
});
JSFiddle
And yes, as other members have pointed out, it would be better if you use data attribute (data-defaultValue) instead.
This is a more compact solution:
var id = $('#id');
id.val(id.attr('default'));
You really don't need to use $(...) every time.
Store your jQuery element in a variable:
var $id = $('#id');
$id.val($id.attr('default'));

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.

Weird Behaviour in jQuery's html method

Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?
Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.
jQuery only accepts a string as an argument for the val parameter of the html() method. If you pass a number like you are it will call the html() method override that sets the contents of the element but the value of the argument will end up being null or an empty string.
Try this:
$("p").html((0).toString())
Relevant documentation
I guess that at some point, it checks if (newContent == false), and doesn't continue with adding any content? I tried looking at the source, but got a bit lost...
I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected.
A workaround would be to do this:
var myNum = 0;
$('p').html('' + myNum);
The code performing the html call was within someone else's plugin and rather than modify it, making upgrading it tedious, I just wrote the following tiny plugin that modifies the html method to do as spoon16 recommended.
(function($) {
var oldHtml = $.fn.html;
$.fn.html = function (content) {
oldHtml.apply(this, [content.toString()]);
}
})(jQuery);
It's a little bit of a hack, but it's working for me and doesn't require me to modify the Plugin I'm using.
I just thought someone else might like to see this.
Try using text() instead html().
I geuss you missed part of how jQuery works,
$('p')
returns all paragraphs and the html( val ) function:
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
http://docs.jquery.com/Attributes/html#val
So if you just want to set the contents for the first p use
$("P").eq(0).html( 'something' );
or to get the html:
$("P").eq(0).html();
http://docs.jquery.com/Core/eq#position
more on jQuery selectors here:
http://docs.jquery.com/Selectors

Categories

Resources