Basically I'm creating an upvote/downvote system, Now I've created two buttons in HTML :
<button type="button" name="upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="downvote"></button>
First button with name attribute - "upvote" and second with "downvote" , Now I want to catch a click on button and change the commentValue accordingly, If user clicks upvote, comment value must incriment and on downvote it must decrement
I found some topics that said to implement ActionListener, Create JButton objects and etc. but isn't there any simpler way ?
This is my code right now, The buttons do nothing. :
Controller :
private int numberValue = 0;
#GetMapping("/check")
public String nuberCheck(Model model){
model.addAttribute("commentValue", numberValue);
return "numberCheck";
}
#PostMapping("/check")
public String upvote(Model model, #RequestParam String action){
if (action == "upvote"){
numberValue++;
model.addAttribute("commentValue", numberValue);
}else if (action == "downvote"){
numberValue --;
model.addAttribute("commentValue", numberValue);
}
return "numberCheck";
}
numberCheck :
<form action="#" th:action="#{/check}" method="post">
<button type="button" name="action" th:value="upvote" th:text = "upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="action" th:value = "dowvnote" th:text = "dowvnote"></button>
</form>
FIXED
Change button types to "submit" and then in controller :
#PostMapping("/check")
public String check(Model model,#RequestParam String action) {
System.out.println(action);
if (action.equals("upvote")) {
numberValue++;
model.addAttribute("numberValue", numberValue);
}
if (action.equals("dowvnote")) {
numberValue--;
model.addAttribute("numberValue", numberValue);
}
return "numberCheck";
}
#RequestParam String action "action" is the name attribute of button and "save" and "cancel" are the "value" attributes :) hope it helps
Sample:
HTML:
<form action="#" data-th-action="#{/action}" data-th-object="${model}" method="post">
<button type="submit" name="upvote"></button>
<button type="submit" name="downvote"></button>
</form>
Java:
#RequestMapping(value="/action", method=RequestMethod.POST)
public ModelAndView onClickAction() {}
Use the following and implement in your code
$(document).ready(function(){
$("#up").click(function(){
var up = $.post("/upvote", {changeBy: 1}, function(dataBack){
$("#upvote").text(dataBack);
});
});
$("#down").click(function(){
var down = $.post("/downvote", {changeBy: 1},
function(dataBack){
$("#downvote").text(dataBack);
});
});
});
You can use jquery for that. first add jquery library in your html page and write function like below inside script tag
function upVote(){
var counter= $('.comment').val();
counter++;
$('.coment').val(counter);
}
function downVote(){
var counter= $('.comment').val();
counter--;
$('.coment').val(counter);
}
<button type="submit" name="upvote" th:onclick="'upVote();'"></button>
<br>
<input type="number" class="comment"th:value = "${commentValue}" disabled>
<br>
<button type="submit" name="downvote" th:onclick="'upVote();'"></button>
There is one best way to solve this. When you click button trigger one event and at that event increase or decrease value. Use that value in an thymeleaf and pass it to the controller.
Related
I'm trying to pass a trackingNo to jsp page based on which button is pressed.
I created 2 buttons, addnew and search.
The addnew is supposed to get the input trackingNo from the input field and pass it to tracking.jsp if it is pressed,
and the search is supposed to get the input trackingNo from the input field and pass it to a home_student_result.jsp.
I'm not sure what is the correct way to do it, so I tried using a nested form with "add" id in one form and "srch" id in another.
After running it, only the top form works. The inner form doesn't work.
Can anyone please help me, or suggest a better way to do it please?
<div>
<form id="add" method="post" action="tracking.jsp">
<i class="fas fa-search"></i>
<form id="srch" method="post" action="home_student_result.jsp">
<input name="target" type="input" placeholder = "Search..." class = "text_search"/>
</form>
</form>
</div>
<button class="button_search" onclick="document.getElementById('add').submit()">
Add New
</button>
<button class="button_search" onclick = "document.getElementById('srch').submit();">
Search
</button>
You can use only one form and click of button you can change the action value to particular value depending on button click and then submit your form.
Demo Code :
function submit(value) {
console.log(value)
//if value is add
if (value == "add") {
//change action of form
document.getElementById('forms').action = 'tracking.jsp'
document.getElementById('forms').submit(); //submit
} else {
document.getElementById('forms').action = 'home_student_result.jsp'
document.getElementById('forms').submit();
}
}
<div>
<!--add id to form-->
<form id="forms" method="post" action="tracking.jsp">
<i class="fas fa-search"></i>
<input name="target" type="input" placeholder="Search..." class="text_search" />
</form>
</div>
<!--add function with parameter(value of button) -->
<button class="button_search" value="add" onclick="submit(this.value)">
Add New
</button>
<button class="button_search" value="srch" onclick="submit(this.value)">
Search
</button>
You can keep both the forms independently and set the value of 'target' field using javascript. something like below .I've added id attributes to your code to work with vanilla javascript.
<div>
<form id="add" method="post" action="tracking.jsp">
<i class="fas fa-search"></i>
<input id="addText" type="input" placeholder = "add text"/>
<button class="button_search" onclick="addToSearch()">
Add New
</button>
</form>
<form id="srch" method="post" action="home_student_result.jsp">
<input name="target" id="searchValue" type="input" placeholder = "Search..." class = "text_search"/>
<button class="button_search" onclick = "document.getElementById('srch').submit();">
Search
</button>
</form>
</div>
<script>
function addToSearch(){
var textValue = document.getElementById('addText').value;
document.getElementById('searchValue').value = textValue;
}
</script>
I have a problem and I don't know how to think about it anymore.
I have a window that shows a list of activity types in a table that loads from BD. I have several action buttons set for each row, including delete and edit. The problem that appears to me is that when I give any of the two buttons, they always call the POST method. I have both with the PUT and the DELETE but they do not go through there and always go to the POST.
I put the controller and html code to see if someone sees something that is being overlooked.
Class Tipo_Actividad_ServicioController:
#Controller
public class Tipo_Actividad_ServicioController {
#Autowired
private Tipo_Actividad_ServicioService tipo_Actividad_ServicioServcie;
#RequestMapping(value = "/tipo_actividad_servicio", method = RequestMethod.GET)
public String findAll(Model model) {
extracted(model);
return "tipo_actividad_servicio";
}
// Guardar Tipo_Actividad_Servicio
#RequestMapping(value = "/tipo_actividad_servicio", method = RequestMethod.POST)
public String save(Tipo_Actividad_Servicio tipo_Actividad_Servicio, Model model) {
tipo_Actividad_ServicioServcie.save(tipo_Actividad_Servicio);
extracted(model);
return "tipo_actividad_servicio";
}
#RequestMapping(value = "/tipo_actividad_servicio", method = RequestMethod.PUT)
public String saveById(#RequestParam int id, Model model) {
Tipo_Actividad_Servicio tipo_Actividad_Servicio = tipo_Actividad_ServicioServcie.findById(id);
if(tipo_Actividad_Servicio.isActivo())
tipo_Actividad_Servicio.setActivo(false);
else
tipo_Actividad_Servicio.setActivo(true);
tipo_Actividad_ServicioServcie.save(tipo_Actividad_Servicio);
extracted(model);
return "tipo_actividad_servicio";
}
#RequestMapping(value = "/tipo_actividad_servicio", method = RequestMethod.DELETE)
public String deleteById(#RequestParam int id, Model model) {
tipo_Actividad_ServicioServcie.deleteById(id);
extracted(model);
return "tipo_actividad_servicio";
}
private void extracted(Model model) {
model.addAttribute("tipos_actividad_servicio", tipo_Actividad_ServicioServcie.findAll());
model.addAttribute("tipo_actividad_servicio", new Tipo_Actividad_Servicio());
}
}
And the HTML table that calls the delete method.
<tbody>
<tr th:each="familia,iterStat : ${tipos_actividad_servicio}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${familia.id}" style="display:false"></td>
<td th:text="${familia.nombre}"></td>
<td th:text="${familia.tipo}"></td>
<td th:text="${familia.observaciones}"></td>
<td style="display: flex; justify-items: center; align-items: center;">
<div class="btn-group">
<button type="button" class="text-white btn .btn-sm btn-warning" data-toggle="modal" data-target="#modal-lg">
Editar
</button>
<form style="margin: 0px;" th:action="#{/tipo_actividad_servicio}" th:method="put">
<input type="hidden" name="id" th:value="${familia.id}">
<button class="text-white btn .btn-sm btn-success" th:unless="${familia.activo}" type="submit">
Activar
</button>
<button class="text-white btn .btn-sm btn-secondary" th:if="${familia.activo}" type="submit">
Desactivar
</button>
</form>
<form style="margin: 0px;" th:action="#{/tipo_actividad_servicio}" th:method="delete">
<input type="hidden" name="id" th:value="${familia.id}">
<button class="text-white btn .btn-sm btn-danger" th:if="${familia.activo}" type="submit">
Eliminar
</button>
</form>
</div>
</td>
</tr>
</tbody>
This is what the console shows me when it calls the method:
Hibernate: update tipo_actividad_servicio set activo=?, nombre=?, observaciones=?, tipo=? where id=?
When I inspect the form from firefox it tells me that the method is post and that it is going to call the PUT or DELETE ...
<form style="margin: 0px;" action="/tipo_actividad_servicio" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="id" value="2">
<button class="text-white btn .btn-sm btn-secondary" type="submit">
Desactivar
</button>
</form>
The truth is that I no longer know exactly what to do and what to try, if someone could tell me why it doesn't eliminate ...
Thank you.
If you are using Boot 2.3.X then make sure you have enabled the hidden http method filter, spring.mvc.hiddenmethod.filter.enabled=true. This filter is no longer enabled automatically as of 2.3.X. This filter will look at the _method attribute and direct the request to the appropriate controller method.
Hi guys hope you can help me, because i cant get further at the moment
I have my Controller.
#RequestMapping(value="/kundenseite", method= RequestMethod.GET)
public String kundenLogin(ModelMap model) {
if(kundeComponent.getKunde() != null) {
List<Restaurant> restaurants = restaurantService.alleRestaurants();
model.addAttribute("restaurants", restaurants);
return "kundenseite";
}else {
return "redirect:/kunde/login";
}
}
#RequestMapping(value="/kundenseite", method= RequestMethod.POST)
public String kundenLoginAnswer(ModelMap model, #ModelAttribute Restaurant restaurant) {
System.out.println(restaurant.toString());
return "kundenseite";
And my jsp file
<%# include file="common/header.jspf" %>
<div class="jumbotron text-center">
<h1>MiMiMi Lieferservice</h1>
<p>Der schnellste Lieferservice von Passpick</p>
</div>
<div style="margin-right:auto; margin-left:auto; width: 33%">
<h2 style="text-align: center">Restaurant wählen</h2>
<div class="well">
<c:forEach items="${restaurants}" var="restaurant">
<form:form modelAttribute="${restaurant}" method="post">
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.name}</div>
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.restaurantTyp}</div>
<button type="submit">Bestellen</button>
</form:form>
<br style="clear:both;" />
</c:forEach>
</div>
</div>
</body>
</html>
If the user presses a button i want to return a restaurant.
But i don't know how to make that happen, my thought was to use a form but i cant get it to send a complete restaurant object back
If there is no solution for this i have to write the id with the button.
You need input hidden inside the form tab as below input hidden:
<input type="hidden" name="name" value="${restaurant.name}">
<input type="hidden" name="restaurantTyp" value="${restaurant.restaurantTyp}">
I have a radio button really simple in my html file:
<form role="form" method="post" action="jsp/site/Portal.jsp?page=mypage">
<input type="radio" id="radio_1" name="name_radio" value="value1" />
<input type="radio" id="radio_2" name="name_radio" value="value2" />
<button name="action_validateForm" type="submit">
Valider
</button>
</form>
But when i send the form it goes in function :
#Action( ACTION_VALIDATE_FORM )
public Page doValidateForm( HttpServletRequest request )
{
String valueGet = request.getParameter( "name_radio" );
if ( valueGet.equals( "value1" ) )
{
//Do action
}
else if ( valueGet.equals( "value2" ) )
{
//Do other action
}
}
The problem is that no matter the radio button I select before validate the form when I check request.getParameter( "name_radio" ) the value is always false. How can it be possible? it should be value1, value2 or null?
I think you need to add submit button or javascript code to submit your form, then try to fetch radio button value in JSP.
see i have added submit button.
<form role="form" method="post" action="jsp/site/Portal.jsp?page=mypage">
<input type="radio" id="radio_1" name="name_radio" value="value1" />
<input type="radio" id="radio_2" name="name_radio" value="value2" />
<button type="submit" value="Submit">Submit</button>
</form>
Onclick of a form button, I need to call a small javascript function. This javascript function should validate some fields in the same form and then call the onSubmit() of the form which is in java.
Main Idea is that let validate happen in client side and not in java.
Complete idea :
I have help.html file as shown below :
<form wicket:id="form">
<input type="text" wicket:id="one"/>
<input type="text" wicket:id="two"/>
<input type="submit" wicket:id="save"/>
</form>
In help.java, I created a WebMarkupContainer and added this form with this submit button :
container.add(new Button("save") {
#Override
public void onSubmit() {
//saved
}
});
On click of the button in html, it calls onSubmit() and here we can do a validation on the text box values.
But I need to do all the validations in the HTML page itself.
OnClick of the Button Save, it should call a javascript funciton as shown below :
<form wicket:id="form">
<input type="text" wicket:id="one"/>
<input type="text" wicket:id="two"/>
<input type="submit" wicket:id="save" onclick="validateRange()"/>
</form>
JavaScript :
function validateRange(){
//logic
//Submit the form
}
Can this be done?
You need an AjaxSubmitLink or something like this. The you need to create a new IAjaxCallListener
public class MyAjaxCallListener implements IAjaxCallListener{
#Override
public CharSequence getBeforeHandler(Component component) {
return YOUR_JAVA_SCRIPT;
}
#Override
public CharSequence getBeforeSendHandler(Component component) {
return YOUR_JAVA_SCRIPT;
}
// ... not needed overrides can return null
}
Then in your AjaxSubmitLink you can add this AjaxCallListener
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new MyAjaxCallListener());
}
Here you have an example Try if yourself
HTML:
<form id="form" action="#">
<input id="text" type="text"/>
<input type="button" onclick="validate()" value="TEST"/>
</form>
JS:
function validate() {
var value = document.getElementById("text").value;
if (value == "") {
alert("you have to write something");
return false;
}
else
document.getElementById("form").submit();
}