Add Variable inside th:onsubmit thymeleaf - javascript

I'm trying to add variable inside th:onsubmit with
th:onsubmit="return confirm('Hi '" + ${user.name} + "')"
but it always get me error like
Malformed markup: Attribute "+" appears more than once in element
also i can't find onsubmit example on thymeleaf official document

There is nothing special about onsubmit which is why there is nothing in the official documentation about it -- you're simply not formatting the expression correctly. I would format the expressions like this:
th:data-username="${user.name}"
onsubmit="return confirm('Hi ' + this.getAttribute('data-username'))"
(To avoid security errors, Thymeleaf may prohibit you from concatenating strings directly in your JavaScript, which is why I'm separating it out to it's own attribute.)

You can use a function in your onsubmit event, and assign the Thymeleaf expression to a variable within that function.
Example (using onclick in my case):
<yourtag ... onclick="runMyFunction();"></yourtag>
...
<script th:inline="javascript">
function runMyFunction() {
var user_name = [[${user.name}]];
console.log(user_name);
}
</script>
This uses Thymeleaf's JavaScript inlining syntax [[${...}]].
Note that in this case, the event does not have to be th:onsubmit - just onsubmit.

Related

Issue in calling a function using string literals(template literals) when click on a button

So basically I want to call a function with a parameter when I click a button. And the button is created using a string literal.
function showNewUserOnScreen(user) {
let parentNode = document.getElementById("listOfUser");
let childhtml = `<li> ${user.username} - ${user.email}
<button onclick = ${() => deleteUser(user.email)}> Delete </button>
</li>`;
parentNode.innerHTML = parentNode.innerHTML + childhtml;
}
The above image is the code that I have written, and now would like you to look at the below image of how the code gets its output in the browser.
This second image is what I get in the browser. Now when I click on this delete button it gives me the error as shown in the below image
Uncaught SyntaxError: Unexpected token ')' (at localstorage.html:1:2)
This doesn't work in the way you think it does (or should). Template literals will evaluate the contents of the expressions you enclose in ${}, so an expression representing a function definition won't evaluate to much of anything useful in this context.
If you're intent on using inline on* parameters and generating DOM elements from HTML strings (both no longer recommended practices in favor of using addEventListener() and createElement()/appendChild() (and other DOM manipulation methods), respectively), just include the name of the function you want to run on that event and use the template literal portion to pass just the string argument:
let childhtml = `<li> ${user.username} - ${user.email}
<button onclick="deleteUser('${user.email}')"> Delete </button>
</li>`;
This will lead to issues (including security issues) down the road if user.email can contain apostrophes (' or "); as such I would recommend switching to the more modern syntaxes I mentioned above (among other reasons).

Function parameter used in jQuery selector

I have an event handler that appends a new row to a table.
$("#pre_script_12").change(function() {
$("#selected_pre_scripts")
.append("<tr><td><a href='javascript:moveScriptUp("
+ this.id
+ ")'>Move</a></td></tr>");
moveScriptUp() looks like this:
function moveScriptDown(id) {
current = $("tr." + id).eq(1);
$(current).prev().before($(current).next());
$(current).prev().before($(current).next());
}
However, I am getting an error when when appending id to tr..
Error: Syntax error, unrecognized expression: tr.[object HTMLInputElement]
How can I supply the id as a parameter to the above JavaScript function without getting this error when attempting to use it in a jQuery selector?
You need to quote strings in your function call.
Right now, your <a> tag looks like this:
<a href='javascript:moveScriptUp(pre_script_12)'>Move</a>
In (most) browsers, all elements IDs become a global variable, so pre_script_12 refers to the element. You need to add quotes, so you're passing a string:
$("#selected_pre_scripts")
.append("<tr><td><a href='javascript:moveScriptUp(\""
+ this.id
+ "\")'>Move</a></td></tr>");
P.S. I highly reccomend, not using inline JavaScript. Why not bind a (delegated) event handler to call the moveScriptUp() function?

cannot pass string to function

I'm using javascript and I try to pass a string to a function , like so
//example string
var f="a";
//add button that sends the value of f to the function
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere("+f+");'> ";
function gothere(a){
alert(a);
}
I never see the alert and in console I see a is not defined (refers to the f I guess?)
If i set the f var to be a number then I see the alert.
What am I missing?
Thanks in advance
EDIT
I was thinking maybe something like
var buttonnode= document.createElement('input');
document.getElementById("mydiv").appendChild(buttonnode);
buttonnode.onclick=gothere(f);
Wont work for the same reason?
When your HTML get's rendered, you get onclick='gothere(a);', but the actual a variable doesn't exist in this context, you want to pass the value of f, as a string, so you'll need to use onclick='gothere(\""+f+"\");'. Note the extra quotes inside the parens. This will render to onclick='gothere("a");' thus passing the string.
When using a number, it works, because calling onclick='gothere(5);' is valid, since a variable can't be named 5, and it passes the number.
Actually, you don't have an a in your code. You are using variable f to denote a. So using this would help you:
var f="a";
// write the remains of the code as they are..
function gothere(f) {
alert(f);
}
Now when you'll call the function, there will be an alert of a in the browser.
Also, try wrapping the content in "" double qoutes to let the code understand that this is a string not a character.
For onclick use
onclick='gothere(" + f + ")'
And now, its onto you to write the value. Maybe the issue is because you're not writing the value for the f.
Try inpecting the error. I am sure there won't be anything.
Or try using the attribute field and change it using jQuery.
How about fixing your code ? You are missing the quotes around the value denoted by variable F.
Hence, when variable F is parsed, the function becomes gothere(a) . while a is not a defined variable (but its a value) and hence the error.
Try this !
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere(\""+f+"\");'> ";
The modified part is onclick='gothere(\""+f+"\");'> "
This should work for you !
function parameter string value image dynamically from JSON. Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter.
My Function Onclick inside pass parameter.
items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+" onclick='changeImage(\""+item.product_image2+"\");'>";
My Function
<script type="text/javascript">
function changeImage(img)
{
document.getElementById("saleDetailDivGetImg").src=img;
alert(img);
}
</script>
You need to use single quotation marks for value arguments (see #Nis or #CDspace answer).
Better way to handling dynamic clicks or other events is event binding. See jQuery event binding for example.

Using strings containing single quotes as Javascript arguments within inline HTML

Consider the following Javascript (which is probably not the best style):
var string = "There's an error here";
parent.innerHTML = '<div onclick="foo(\'+string+\')">'+string+'</div>';
Because of the single quote, the resulting HTML is not valid:
'<div onclick="foo('There's an error here')">There's an error here</div>'
One solution is to use the element's own innerHTML as the argument to foo() (since the function argument happens to be the same as the content of the element). However, this isn't a general solution.
Is it possible to deal with this issue using only an inline HTML solution? In my case, the inline HTML is much larger, and I can't easily convert it to a more 'proper' form, using DOM functions to create and append the HTML, and closures for the onclick functions.
I would say that your main issue is trying to attach event handlers using inline attributes instead of using addEventListener. All your issues will vanish if you respect good practices.
myDiv.addEventListener('click', function () {
foo("There's an error here");
});
However, if you still want to do it your way, you could simply escape the single quotes:
parent.innerHTML = '<div onclick="foo(\'' + string.replace(/'/g, "\\'") + '\');">' + string + '</div>';

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