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

Enhance Your Website with Interactive Tooltips Using Twitter Bootstrap

In Twitter bootstrap, the default trigger for tooltips is hover. If I want to make the tooltip display on focus instead, I can add data-trigger="focus". But how do I make it so the tooltip displays both on hover and on focus? ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Using information retrieved from a JSON response

In my current project, I have set up a JavaScript object within a script tag. <script> searchdata = {"employees":[{"name":"john doe","sal": "10000"}]}; </script> I am utilizing the searchdata object in various functions as shown below: fu ...

All JSON attributes share identical names

When dealing with JSON objects, it is essential that keys are unique (see Does JSON syntax allow duplicate keys in an object?). However, imagine having a file like the one below: { "a" : "1", "b" : "2", "a" : "3" } Is there a straightforward ...

Searching for real-time data with ajax. Strategies for showing alternative results when there is no user input

I am currently working on developing a live search feature using technologies like ajax, jQuery, PHP, and MySQL. The user inputs certain queries which are then sent to form_livesearch.php where the search is processed. I have successfully implemented this ...

The lifecycle of XMLHTTPRequest objects in JavaScript - from creation to destruction

After years of working with traditional compiled object-oriented languages like C++ and .NET programming, I decided to dip my toes into JavaScript for a new project. As I was experimenting with AJAX, I stumbled upon a perplexing aspect related to how objec ...

Modifying the information depending on the option chosen from the dropdown menu using angularJS

I have a dropdown menu where I can choose between two options, and when selected, the corresponding data is displayed. However, I would like to display the data that is inside a div tag instead. Check out this Fiddle Demo HTML: <div ng-controller="Ct ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Could not parse JSON after php file update. Everything was fine before switching to PDO, but now encountering a parsing issue

I encountered an issue where I could log in using a member from the database (MySQL) using Chrome, and create a new user successfully. However, when I tried to use the app, it crashed after attempting to create a new user. After testing some simple PHP co ...

Angular 2 template is nowhere to be found

As a newcomer to Angular 2, I am currently developing an app where I have successfully completed the Root component containing a navigation bar and footer. However, as I delve into working on the homepage module, I encountered an error. [Error] Unhandle ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

What is the best way to transfer data between functions?

I'm working on a fun Santa's game to play with my friends. The concept is simple: you enter your name, click a button, and a random name from the list will be displayed as the result. I've encountered a couple of challenges: I can succe ...

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

Fetching data using ajax and then appending it to the webpage

I am currently loading content from a PHP file in JSON format. products.php <?php $stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10"); $stmt->execute(); $products = $stmt->get_result(); $produc ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

Preventing default behavior in a JQuery post request

Encountering an issue with jQuery functionality on a mobile device. function send() { $.post("scripts/post.php", { username: $("input[name=username]").val(), password: $("input[name=password]").val() }, function(data) { if ($(".data div" ...

The functionality of CSSTransition seems to be malfunctioning. Perhaps switching to V2 of react

Can anyone help me troubleshoot my code snippet where I'm attempting to incorporate an animation for Tooltip Nodes? Despite my efforts, the animation does not show up on the screen after mounting. Additionally, the console.log is not triggered on the ...

Bootstrap-tour is incompatible with a row within a table structure

Is there a way to highlight a table row effectively? I've been struggling with it and tried using the fix mentioned in this bootstrap-tour issue here Check out this demonstration on jsFiddle: jsFiddle JAVASCRIPT $("#dialog").dialog(); var t = new ...

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...