On the input form, I perform a check of the entered cost value. But running the script can't find the form input input01.
That's how it works:
<form name="form01" th:method="POST" th:action="#{/add-car/new}" th:object="${carEntity}">
<input type="text" name="input01">
...
<button type="submit" class="btn btn-primary" onclick="check()">Save</button>
</form>
<script>
function check() {
let inputVal = document.forms["form01"]["input01"].value;
OK!!!
....
}
</script>
But not like this:
<form name="form01" th:method="POST" th:action="#{/add-car/new}" th:object="${carEntity}">
<input type="text" name="input01" th:field="*{cost}">
...
<button type="submit" class="btn btn-primary" onclick="check()">Save</button>
</form>
<script>
function check() {
let inputVal = document.forms["form01"]["input01"].value;
Where Error:
"Uncaught TypeError: document.forms.form01.input01 is undefined"
....
}
</script>
What am I doing wrong?
As per https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html,
<input type="text" th:field="*{datePlanted}" />
is equivalent to
<input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />
Hence when you add th:field="*{cost}", the form element name and id is getting changed to name="cost" id="cost". so document.forms["form01"]s input element will look like
<input type="text" name="cost" id="cost">
Either access the element as
document.forms["form01"]["cost"]
Or add a form id like below and your existing code should work.
<input id="input01" type="text" name="input01" th:field="*{cost}">.
Hope that helps to solve your problem.
Related
I want to use a form without an object. How to display errors?
Controller:
#PostMapping(value="/submit")
public String doSubmit(#RequestParam("myParameter") String param, BindingResult bindingResult) {
bindingResult.rejectValue("myParameter", "Oh nooo!!!!");
return "html";
}
HTML:
<form th:action = "#{/submit}" method="post">
<label for="myParameter" class="form-label">My Parameter</label>
<input name="myParameter" class="form-control" type="text"/>
<span class="text-danger" th:if="${#fields.hasErrors('myParameter')}" th:errors="myParameter">Error</span>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
th:if="${#fields.hasErrors('myParameter')}" th:errors="myParameter" throws errors, cause "myParameter" is not known.
How to display the error, without using th:object in <form>
I did it with the help of this question Thymeleaf: display global errors by error code
#PostMapping(value="/submit")
public String doSubmit(#RequestParam("myParameter") String param, BindingResult bindingResult) {
bindingResult.reject("myParameter", "myParameter");
return "html";
}
Important: myParameter must not be a key of a message source!
<form th:action="#{/submit}" method="post">
<label for="myParameter" class="form-label">My Parameter</label>
<input name="myParameter" class="form-control" type="text"/>
<span class="text-danger" th:if="${#lists.contains(#fields.globalErrors(), "myParameter")}" th:text="An Error happened">Error</span>
<button type="submit" class="btn btn-primary">Submit</button>
Important: Use " to indicate the string. th:text? may contain a message key like th:text="#{error.code1}"`.
I have a list of objects as JSON which is inside a workLists. I created a table by iterating using each on workLists and create a table in thymeleaf?
Now how can I pass work that is a single object back to the controller, what I tried is using th:object
I thought it would work but on the controller end null values are coming.
Thymeleaf section
<tr th:each="work , status : ${workLists}">
<td scope="row" th:text="${status.count}"></td>
<td>
<form th:action="#{/edit/work}" th:object="${work}" method="post">
<button type="submit" class="dropdown-item">Edit</button>
</form>
</td>
</tr>
Controller Section
#PostMapping("/edit/work")
public String editWork(#ModelAttribute("work") GetWorkkDto getWorkDto){
logger.debug(" Inside of edit work method");
return "listOfwork";
}
You need to give the contoller 2 attribues which are the workLists and a work. It will be something like:
#GetMapping("/edit/work")
public String editWork(Model model){
model.addAttribute("workLists", workLists);
model.addAttribute("workDTO", new Work());
return "listOfwork";
}
Then in your HTML page through hidden fields you give the values of the work selected:
<table>
<tr th:each="work, stat : ${workLists}">
<td>
<form action="#" th:action="#{/edit/work}" th:object="${workDTO}" method="post">
<input type="hidden" th:attr="name='id'" th:value="${work.id}" />
<input type="hidden" th:attr="name='name'" th:value="${work.name}" />
<input type="hidden" th:attr="name='description'" th:value="${work.description}" />
<p th:text="'Id : '+${work.id}"></p>
<p th:text="'Name : '+${work.name}"></p>
<p th:text="'Description : '+${work.description}"></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</td>
</tr>
</table>
You can see in the proposed code that I give the value of work.id to the workDTO.id through the name attribute (don't ask me why it is like this)
Finaly you retrieve the object in your controller (as you do already) with something like this:
#PostMapping("/edit/work")
public String editWork(#ModelAttribute Work workDTO, Model model){
System.out.println(workDTO.toString());
model.addAttribute("workLists", workLists);
model.addAttribute("workDTO", new Work());
return "listOfwork";
}
i'm beginner with Thymeleaf, but i want know how to call a method in HTML with Thymeleaf. I'm using Spring Boot with Spring MVC.
I want create a Button with a name like "Edit" and the user will edit the post of the blog, but if i want do that i have to know what's the ID from object Postagem.
My current code HTML: (blog.html)
<div th:each="postagem : ${postagens}">
<div class="blog-post">
<h2 class="blog-post-title" th:text="${postagem.titulo}"></h2>
<p class="blog-post-meta">25 de dezembro de 2019 publicado por Vitor</p>
<p th:text="${postagem.texto}"></p>
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<button type="submit" class="btn btn-link" th:field="*{id}">Editar</button>
</form>
</div>
<!-- /.blog-post -->
</div>
My current method in Java: (PostagemController.java)
#PostMapping("/blog")
public String edit(Postagem postagem) {
for(Postagem post : postagens.findAll()) {
if(post.getId() == postagem.getId()) {
ModelAndView modelAndView = new ModelAndView("painel");
modelAndView.addObject("postagemEdit", post);
System.out.println("Id: " + post.getId());
System.out.println("Título: " + post.getTitulo());
System.out.println("Autor: " + post.getAutor());
System.out.println("Texto: " + post.getTexto());
break;
}
}
return "redirect:/painel";
}
My current code on "painel.html" where is my form that I want set the information
<form method="post" th:object="${postagemEdit}" th:action="#{/painel}" style="margin: 20px 0">
<div class="form-group">
<input type="text" class="form-control" placeholder="Título" th:field="*{titulo}" /> <br>
<input type="text" class="form-control" placeholder="Spoiler do artigo" th:field="*{spoiler}" /><br>
<input type="text" class="form-control" placeholder="Autor" th:field="*{autor}" /> <br>
<textarea id="mytextarea" th:field="*{texto}"></textarea> <br>
<button type="submit" class="btn btn-primary">Publicar</button>
</div>
</form>
It appears that you have not given the id a value in the html code. The default value for int in Java is 0 and that is possibly the reason why. Try to use 1 instead of *{id}.
If you are retrieving the blog post id and post content from the database which should be so then this problem will be solved.
issues
No name
Value not set
solution 1
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<input type="hidden" name="id" class="btn btn-link" th:value="*{id}" />
<button type=submit class="btn btn-link">Editar</button>
</form>
solution 2
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<button name="id" type=submit class="btn btn-link" th:value="*{id}">Editar</button>
</form>
solution 3
function myFunction(id) {
var f = document.createElement("form")
f.style.display="none"
f.action="/action_page.php"
f.method="get"
var inp = document.createElement("input");
inp.value=id
inp.name="id"
f.appendChild(inp);
document.body.appendChild(f);
f.submit();
}
<button type=submit class="btn btn-link" th:data-id="*{id}" onclick='myFunction(this.getAttribute("data-id"))'>Editar</button>
Following is the working code that i used in the html template to call java class function
<small th:text="${T(com.sample.util.UIclass).textContent(instr)}"> </small>
And below is the java class for the method :
package com.sample.util;
import com.sample.models.Instr;
public class UIclass {
public static String textContent(Instr instr)
{
return "Hello";
}
}
In case if you need to access same in javascript following is the code
let d = [[${T(com.sample.UIclass).textContent(instr)}]];
console.log(d);
İ have a form. When user click submit button, i want to show alert and submit the form.
Here is my code sample.
<form action="DoMakeApplication" Method="post">
<td>
<button class="btn type7 color1" type="submit" id="makeApplication" onclick="makeApp();return false" >Başvur</button>
</td>
<input type="hidden" th:value="${jobAdvert.company.companyName}" name="companyName" ></input>
<input type="hidden" th:value="${jobAdvert.company.id}" name="companyId" ></input>
<input type="hidden" th:value="${jobAdvert.id}" name="advertId" ></input>
</form>
This should do the trick:
<form action="DoMakeApplication" method="post" onsubmit="alert('you submitted the form');">
You can proceed as follows:
HTML
<form action="DoMakeApplication" method="post" id="my-form">
<td>
<input class="btn type7 color1" type="submit" id="makeApplication" value="Başvur">
</td>
<input type="hidden" th:value="${jobAdvert.company.companyName}" name="companyName" ></input>
<input type="hidden" th:value="${jobAdvert.company.id}" name="companyId" ></input>
<input type="hidden" th:value="${jobAdvert.id}" name="advertId" ></input>
</form>
JavaScript
document.getElementById('my-form').onsubmit = function () {
alert(42);
};
DEMO
Try
$("#makeApplication").on("click", function(e){
e.preventDefault();
alert("alert here");
// use either of the following
//$(this.form).submit();
//$(this).parents('form:first').submit();
//$("form-id").submit(); // best one
});
YOu can do it like Minko said or you can attach event directly on your button.
In a javascript file write:
$( "#buttonId" ).click(function() {
alert( "Hello, i'm an alert" );
});
THen remember to add your javascript file to your project
You can do it like this using java script.
<script type="text/javascript">
function myalert(){
alert("Form is submitted");
}
</script>
</head>
<body>
<div>
<form action="" method="POST">
<table>
<tr>
<td>Username</td>
<td colspan="" rowspan="" headers=""><input type="text" name="username" value="" placeholder="enter username"></td>
</tr>
<tr>
<td>Password</td>
<td colspan="" rowspan="" headers=""><input type="password" name="password" value="" placeholder="enter password"></td>
</tr>
<tr>
<td colspan="1" rowspan="" headers="" align="right"><input type="submit" name="login" value="Login" onclick="myalert()" placeholder=""></td>
<td colspan="1" rowspan="" headers="" align="right">Click to signup</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Alok is correct in case you want to give an id to your form you can do it like this:
$( "#yourFormId" ).submit(function( event ) {
event.preventDefault();
alert( "some alert message" );
});
I have 2 textboxes and 3 buttons and each button has specific action i.e. insert, update, delete.
But how to redirect it when specific button click ?
because i have used it in one form tag.
so what will it do when any button click ?
how it will get the action name ?
code :
<form action="Doaction" method="post">
First Name : <input type="text" id="fname" name="fname">
<br>
Last Name : <input type="text" id="lname" name="lname"><br>
<input type="button" value="Insert">
<input type="button" value="Update">
<input type="button" value="Delete">
</form>
any help please ?
in form : give name to buttons
First Name : <input type="text" id="fname" name="fname">
<br>
Last Name : <input type="text" id="lname" name="lname"><br>
<input type="button" value="Insert" name="button">
<input type="button" value="Update" name="button">
<input type="button" value="Delete" name="button">
</form>
String button_param = request.getParameter("button");
RequestDispatcher rd = null;
if(button_param .equals("Insert")
{
rd=request.getRequestDispatcher("InsertServlet");
}
else if(button_param .equals("Update"))
{
rd=request.getRequestDispatcher("UpdateServlet");
}
else if(button_param .equals("Delete"))
{
rd=request.getRequestDispatcher("DeleteServlet");
}
rd.forward(request, response);
you can create a common javascript function like submitForm('pass your action').
Here you can see that function has a parameter. you have to pass action based your requirement
for example :
<input type="button" value="Insert" onclick="submitForm('InsertURL');">
<input type="button" value="Update" onclick="submitForm('UpdateURL');">
Action function body like :
function submitForm(action){
//send Ajax Request to server...using action
}
Yes I have solved it.
I have given a common name to each button and in servlet i have first checked that from which button action call then as per it i have used if condition and inside it's block i have make a related code.
code :
<form action="Doreg" method="post">
First Name : <input type="text" id="fname" name="fname">
<br>
Last Name : <input type="text" id="lname" name="lname"><br>
<input type="submit" value="Insert" name="kb">
<input type="submit" value="Update" name="kb">
<input type="submit" value="Delete" name="kb">
</form>
java code :
String fname =request.getParameter("fname");
String lname =request.getParameter("lname");
String f = request.getParameter("kb");
if (f.equals("Insert"))
{
obj.connect();
String query ="insert into user(firstname,lastname) values('"+fname+"','"+lname+"')";
obj.passquery(query);
}
else if(f.equals("Delete"))
{
obj.connect();
String query ="delete user where firstname='"+fname+"' OR lastname='"+lname+"'";
obj.passquery(query);
}