How can I define an attribute as a variable? - javascript

I'm trying to define the following line as a variable in Jquery by using
var attributeID = $("#element_to_pop_up").attr("attrId");
The link I am using is and attrId is a variable
<a id="element_to_pop_up" attrId="variable">Link</a>
Basically, I am trying to define the value of my attribute "attrId" as a variable.
One more thing to note This is within a FreeMarker template so FreeMarker is already giving me my variable value. I don't have to do an onclick to get the value.
Is there a better way of doing this?

HTML5 supports the notion of data attributes for application-specific uses. So a better approach is to name all your attributes with the data- prefix:
<a id="element_to_pop_up" data-attrid="variable">Link</a>
To include the information that #chris97ong added, the way to access this variable data using jQuery is:
var x= $('#element_to_pop_up').data('attrid');

Related

Dont understand jQuery .attr() Parameter

$newUser.addClass(newTweet.user).attr('data-user', newTweet.user).text('#' + newTweet.user + ': ');
var user = $(this).data('user');
On line 1 newTweet is an object, but I don't understand the parameter 'data-user. This isn't referenced in any of the other files, user, so is the 'data-' prefix performing some action? Or does it somehow reference line 2? Or am I completely wrong in both situations, I also don't understand how .addClass() method is working in this situation. How does a property of an object get added as a class?
The .attr() function adds an attribute to an element. You can read more about it here: http://api.jquery.com/attr/.
data-user is the name of the attribute added to the element. It doesn't provide any actions, but it's used to store data.
The data-* attributes is used to store custom data private to the page or application.
The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.
The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).
The data-* attributes consist of two parts:
The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
The attribute value can be any string
Note: Custom attributes prefixed with "data-" will be completely ignored by the user agent.
https://www.w3schools.com/tags/att_global_data.asp.
Both for the .attr() call and .addClass() it uses the value of newTweet.user, which might be a string.

Assign an object variable from Twig to javascript

Using this syntax (according to Pass variable from twig to js):
var channelData={{ ChannelDataFeed }};
was rendered as a descriptive string of the object (which then caused an error in the js since I didn't use quotes).
I don't want to copy each attribute from the Twig variable since it's tedious, so I'm looking for a way to assign the variable as a whole.
Is there a way to do that? Thanks.

Accessing javascript object named via php globally

I have a bunch of CSS properties stored in a MySQL database accessed via PHP. I need to make these properties available to JavaScript after the page has finished loading.
So what I did is foreach row, put the values in a Javascript object like so:
foreach ($cellcontent as $cellproperty) {
echo 'var '.$cellproperty->cell_id.' = {cellwidth:"'.$cellproperty->cell_width.'"};';
}
(For simplicity's sake I've only included one object property here but in reality there are many more.)
My problem is that at runtime, via JavaScript I get the cell_id reference which is somewhere in the html page like so:
var dacell = $(this).closest("div");
var cellid = dacell.attr("id");
So at this point, cellid is equal to the name of my var from the php output.
But when I try to get the property of my object (cellwidth) via JavaScript it doesn't work. Says its undefined when I try to see the value in an alert:
alert(cellid.cellwidth);
I think I'm just not referencing the actual object at this point and just trying to get a property of what has now become a string.
Is there a way to get back the reference to the object itself?
var cellid = dacell.attr("id");
The variable cellid is a string. Your hopes would be that the variable your are looking is in the global namespace which you can access via the following:
window[cellid].cellwidth
It's an awfull practice to pollute the global namespace with so much stuff.
Fetch all the values you need to inject into the JS, create an associative Array and inject it as a single JSON into the Page.
Nevermind everyone. The eval() javascript function fixed it all.
Instead of doing:
alert(cellid.cellwidth);
I did:
alert(eval(cellid).cellwidth);
and everything worked.
Thanks for all your time.
Cheers,
Erick P.

How to set javascript variable to flask template variable using javascript

I want to set the javascript variable value to flask template variable in javascript. What I am trying is
$(document).on("click", ".prepopulate", function () {
var myBookId = $(this).data('id');
alert(myBookId); // The value is showing proper
{% set tempVar = 'myBookId' %}
alert ({{tempVar}})
});
But it's giving an error instead (UndefinedError: 'list object' has no attribute 'myBookId'). What is the way to set the template variable in javascript using javascript variable?
You want to use set like this:
%SET{"tempVar" value="myBookId"}%
You cannot do this because jinja runs before the page loads and on the server side but the javascript code is executed when the page is loading and on the client side (browser) so your myBookId variable doesn't exist for jinja (see this answer for more info). A way to achieve what you want is to use ajax. See here an example.
If you look at your rendered HTML you will see
alert (myBookId)
Unless you define a variable called myBookId, this is not valid JavaScript. You need to wrap the string value in quotes.
alert('{{ myBookId }}')
An even better way to do this is to let Jinja decide for you if quotes are needed.
alert({{ myBookId|tojson|safe }})
This will wrap string values in strings, leave integers alone, and use JavaScript booleans.

Variable expression into javascript without using th:inline

I searched first but I found confusing answers since I'm new to Thymeleaf and amateurish at best at javascript.
I just want to know how to pass variable expressions into javascript functions, sort of like in JSP:
Button
Of course, this fails with Thymeleaf and passes the string ${contact.id} instead of its value, so how could I get the value of the variable expression instead?
The reason I want it this way is because it depends on the row which is being iterated by th:each.
If there's no other way except to use th:inline, then what's the best approach considering the above statement?
This one worked:
th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'"
Thanks goes out to the thymeleaf forum:
http://forum.thymeleaf.org/variable-expression-into-javascript-without-using-th-inline-td4025534.html
In Thymeleaf version 2.1, I have not been able to get the accepted answer to work. I did find some guidance from a Twitter post from Thymeleaf. Rather than using th:onclick, you use th:attr and specify the onclick attribute therein.
th:attr="onclick='javascript:getContactId(\'' + ${contact.id} + '\');'"
You can not put javascript variables into onclick or other DOM attributes. The value of onclick or any other DOM attribute should be a constant string.
However, you can dynamically modify value of onclick attribute from javascript, like this:
yourDomElement.onclick = anyVariable;
You can do this like:
th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'"
A more generic approach, if you need in JS something that isn't passed as a event handler parameter:
th:attr="data-myValueFromThymeleaf=${contact.id}"
Any attribute whose name is starting with data- is ignored by all browsers. So it won't affect the UI and you can easily read the value in javascript.
I prefer this because it's not ideal to put javascript code in html (see unobtrusive javascript)
I have asked the Thymeleaf project on twitter, and their answer is:
You can use both the "+" operator or literal substitutions. For example: <a th:href="|javascript:change('start','${taskId}')|">
For more info: https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
I have tried, and it works~

Categories