Update the value of input within a Struts2 iterator by utilizing JavaScript

As a junior programmer, I am trying to update the value of an input type text within a Struts2 iterator without refreshing the entire page. I believe using JSON could be a solution for this issue.

Here is my JSP code:

<input type="text" name="cantidad" id="cantidadIndividual" readonly="readonly" value="<s:property value="#a.cestaUnidades"/>">
    <img src="../Imagenes/Administracion/Signo_Mas.png" id="mas" onclick="MasMenosCantidad('+',<s:property value="#a.cestaUnidades"/>,<s:property value="#a.cestaId"/>,<s:property value="#a.ropaStock.rostockUnidades"/>);"/>

    <script>
            function MasMenosCantidad(valor,cantidad,id,stock){
                document.getElementById("clave").value = id;
                if(valor == '+'){
                    cantidad++;
                }
                if(valor == '-'){
                    cantidad--;
                }
                if(cantidad <= stock){
                    document.getElementById("cantidadIndividual").value = cantidad;
                    usarAJAXCantidad(id,cantidad);
                } else {                    
                    if(valor == '-'){
                        document.getElementById("cantidadIndividual").value = stock;
                        usarAJAXCantidad(id,cantidad);
                    } else {
                        alert("Stock excedido");
                    }
                }
            }
            function usarAJAXCantidad(clave,cant){
                $.getJSON('ajaxCantidad', {
                    clave : clave,
                    cantidad : cant
                }, function(jsonResponse3) { 
                    var nuevaCantidad = $('#cantidadIndividual');
                    $.each(jsonResponse3.stateMap3, function(key, value) {
                        nuevaCantidad.value = value;
                    });
                });
            }            
        </script>

The Struts.xml configuration:

<action name="ajaxCantidad" class="Acciones.HomeCesta" method="ajaxCantidad">
            <result type="json">
                <param name="excludeNullProperties">true</param>
                <param name="noCache">true</param>
            </result>
        </action>

In HomeCesta.java:

public String ajaxCantidad() throws Exception {

        c = ControladoresDAO.cCesta.RecuperaPorId(clave);
        c.setCestaUnidades(cantidad);
        ControladoresDAO.cCesta.Modifica(c);
        stateMap3.clear();
        stateMap3.put("", ""+cantidad);
        return SUCCESS;

    }

My current issue is that when clicking on multiple buttons with the image Signo_Mas.png, only the first input field with id "cantidadIndividual" gets updated. The subsequent clicks do not refresh the correct input field.

Answer №1

When utilizing

document.getElementById("cantidadIndividual")
, only the first element with the same id will be retrieved. To avoid this, it is recommended to make ids unique for each iteration.

In JSP, you can achieve this by using a variable like so:

document.getElementById("cantidadIndividual${uniqueIdentifier}")

Alternatively, if you are working with Struts2:

document.getElementById("cantidadIndividual<s:property value='%{uniqueIdentifier}'/>")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS variable assignment with HTTP GET operation

The angular filter I have set up is functioning perfectly: categorieFilter = angular.module("categorieFilter", []) categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){ $scope.search = ""; $scope.products = []; $ ...

Is there a way to effectively sort out dynamically generated classes in the debug view?

While debugging in Debug View, I noticed dynamically generated classes appearing. Is there a way to filter them out? For instance SomeService$$FastClassByCGLIB$$61115062.invoke(int, Object, Object[]) line: not available MethodProxy.invoke(Object, ...

ui-scroll - unable to return to the start of the list

How can I achieve a scroll downwards and then return to the beginning of the list? I've searched for examples on how to implement ui-scroll back and forth, but none seem to fit my needs. Please assist. You can find the fiddle here: http://jsfiddl ...

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

The WSDL is not fully defined - the Account class does not have a child relationship with a custom object included

After generating an Enterprise WSDL, I noticed that the Account class had numerous fields and relationships with both custom and native objects. However, I realized that the specific relationship I needed for my code was missing. I am puzzled as to why th ...

Instead of using a computed getter/setter, make use of mapState and mapMutations to simplify

Currently, I am syncing a computed value to a component and using a computed setter when it syncs back from the component. I'm wondering if there is a more concise way to replace a computed getter/setter with mapState and mapMutations. How can this b ...

How does Python interpret arrays from JavaScript?

As part of my API setup, I am sending parameters to a python script. One of these parameters happens to be a JavaScript array. Interestingly, when I check the array in Python, it only shows the first index. Here is the snippet of my Angular JS get request ...

Create an XML document containing attributes based on a generic JSON input

I have been working on creating a JSON to XML converter tool, but I'm stuck on how to convert certain JSON properties into XML attributes. For instance, consider the following JSON: { "data" : { "key1" : "value1", ...

How can I display a badge in my app when it is running using React Native?

For the past week, I've been dealing with an issue. My question is how can I display a new message badge without having to click on the message room when running my app. The badge should only show up after clicking on the message room. I see the badg ...

Is it possible to implement sticky sessions with Node.js and pm2?

Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...

What is the best method for converting a variable with HTML content into a printable string?

In an attempt to display user-entered data from a text box to an HTML div, there seems to be an issue when the data contains HTML content. Instead of displaying the content as a string, it shows it as HTML elements. For example: let text = "<h1>Worl ...

Creating a user-friendly form in a Nuxt/Vue application that enables dynamic attribute creation

I am currently working on designing a form that enables users to create different variations for a product within a Nuxt/Vue application. The goal is to provide users with the ability to specify attributes for each variation using a text field. These attr ...

Paste the formatted text from clipboard into the body of a react mailto link

I have a requirement for users to easily send a table via email by copying and pasting it into the subject line. You can view a live demo of this feature on CodeSandbox: copy and paste rich text Below is the function that allows users to copy and paste ri ...

Retrieve the JSON data corresponding to the file that was uploaded

While working on a modified version of the Jquery File Upload Plugin from Hayageek, I encountered an issue. The original code worked perfectly, but when I made modifications to insert the uploaded filename into a database, the JSON response did not include ...

the power of using keywords and prototypes

Greetings! I am currently delving into the realm of JavaScript, hailing from a C++ background. The transition has proven to be quite perplexing for me. Below is a snippet of code that I have been troubleshooting: var someArray = []; nameCompare = function ...

Using Ajax and jQuery to redirect a page with values in ASP.NET

I have two pages: Default.aspx and DetailView.aspx. My goal is to redirect from Default.aspx to DetailView.aspx using an AJAX call and pass a value as well. Although I have tried something, the function defined in the class is not being called. The functi ...

Leveraging javascript to extract data from several input fields and dynamically incorporate them into a table

I'm currently in the process of developing a script that extracts field values and organizes them into a table for verification purposes. The challenge I face is that users have the ability to add multiple fields (up to 5), each with its own unique id ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

Implementing TypeScript with styled components using the 'as' prop

I am in the process of developing a design system, and I have created a Button component using React and styled-components. To ensure consistency, I want all my Link components to match the style and receive the same props as the Button. I am leveraging t ...

The functionality of Log4j seems to have been impacted in the latest version of Java compared to previous versions

After recently upgrading my application from Java 8 to Java 17 and making some library compatibility upgrades, I encountered an issue with the log level not being set as intended. Despite previously setting the log4j log level via code, it is now being fet ...