Having trouble updating a text field on an event using JavaScript - value not defined

When I change the select option, my goal is to dynamically set the value of the input using JavaScript. However, I am encountering an issue where the value becomes undefined.

Below is a snippet from my HTML (JSP) file:

<body>
    <center><h1>Ventas</h1>
        <table border="2">
            <tr>
                <th>Producto</th>
                <th>Precio</th>
            </tr>
            <tr>
                <th>
                    <select name="productos" onchange="ponerPrecio(event)">
                        <c:forEach items="${product}" var="prdct">
                            <option value="${prdct.idProducto}" data="${prdct.precioUnidad}">${prdct.nombre}</option>
                        </c:forEach>
                    </select>
                    <td><input type="text" name="precio" id="price" value="" readonly></input></td>
                </th>
            </tr>
            <script>

                function ponerPrecio(e) {
                    var precio = e.target.getAttribute('data');
                    document.getElementById("price").value = precio;
                }
            </script>
        </table>
        <input type="button" name="begin" value="Inicio" onclick="window.location.href='principal.htm'" />
    </center>
</body>

The ${product} variable provides me with all the items stored in my database for use. The purpose is to utilize the "data" attribute to update the input named "precio" with the value of ${prdct.precioUnidad}.

Answer №1

Try using the data-price attribute instead of just data

<center>
    <h1>Sales</h1>
    <table border="2">
        <tr>                    
            <th>Product</th>
            <th>Price</th>
        </tr>
        <tr>
            <th>
                <select name="products" onchange="setPrice(event)">   
                    <c:forEach items="${product}" var="prdct">
                        <option value="${prdct.idProduct}" data-price="${prdct.unitPrice}">${prdct.name}</option>
                        <option value="2" data-price="10">Custom Item</option>
                    </c:forEach>
                </select>
            </th>
            <td><input type="text" name="price" id="price" value="" readonly></input></td> 
        </tr>        
    </table>
    <input type="button" name="start" value="Home" onclick="window.location.href='main.htm'" />

    <script> 
        function setPrice(e) {
            var price = e.target.options[e.target.selectedIndex].dataset.price;
            document.getElementById("price").value = price;
        }
    </script>  
</center>    

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

Is there a possible method to obtain a smartphone number from a website?

Seeking a solution to retrieve the phone number of a device using HTML 5, JavaScript, or similar technology. Recently, I successfully obtained the coordinates of the device by incorporating the following JavaScript code: <!DOCTYPE html> <html> ...

Which types of characters am I allowed to include in an HTTP response body while using NodeJS and Express?

I am currently developing a node express app that responds to an AJAX post from the client browser. I am curious about what characters would be considered invalid to include in the HTTP response body. My response header specifies the use of charset=utf-8, ...

Locate/place name with AngularJS and Google Maps integration

I need help locating the user-selected location on a map. I currently have the latitude and longitude, but I'm struggling to obtain the location name. My project utilizes angularJS along with angular-google-maps 2.1.5. Below is the HTML code: <u ...

What could be the reason behind the absence of this.props.onLayout in my React Native component?

In my React Native app, I have the below class implemented with Typescript: class Component1 extends React.Component<IntroProps, {}> { constructor(props){ super(props) console.log(props.onLayout) } ... } The documentation for the View ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

Ionic - Retrieve data from a Universal Resource Identifier

When using my application, users have the option to select and crop images using Ionic Native - Crop. Once they have cropped their image, I will receive the URI of the image, for example: file:///storage/emulated/0/Android/data/com.myApp/cache/15353694789 ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

Sending data from a JSP page to a JavaScript function

I am working on a script that dynamically adds text boxes based on a specific time interval. <script type="text/javascript> $(document).ready(function() { var data = $('#data').val(); var counter = 1; var d = new Date(); va ...

Multiple instances of the identical 'Angular application' displayed simultaneously on the webpage

We've created a unique Angular 1.0 application that we aim to embed as a 'widget' within another website built with classic asp.net. During the development phase of our angular app, we take advantage of a range of gulp tools for tasks such ...

React.js: Why does the array index change after dropping an element?

When I create a table with items in a checkbox list, the issue arises; after selecting and submitting some items, the index of the remaining items changes. Consequently, re-submitting the remaining items becomes impossible. Below is my code snippet: expo ...

Is it possible to extract multiple subqueries from the "FROM" clause using JSQLparser?

How can I retrieve all the sub-queries from a FROM clause in SQL? FromItem fromItems = plainSelect.getFromItem(); When using this code snippet, it only retrieves the first sub-query in the FROM clause. Is there a way to get all sub-queries instead of ju ...

Blend multiple images using Angular

Is there a way to combine multiple images in Angular? I came across some HTML5 code that seemed like it could do the trick, but unfortunately, I couldn't make it work. <canvas id="canvas"></canvas> <script type="text/javascript"> ...

What is the process for sending a POST Request to Ghostbin using Node.JS?

I'm attempting to make a POST request to Ghostbin using Node.JS and the request NPM module. Below is the code I have been utilizing: First Try: reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post" }, function (err, res, body) ...

Can Cell be rendered into a targeted element?

Can a Cell from CellJS be rendered into a specific HTML element? For example, including a Cell alongside some static HTML that is not managed by cell. Or having two separate Cell apps on a single page. <!DOCTYPE html> <html> <header> ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Utilize the jQuery autocomplete UI Widget to trigger a select event on a dynamically generated row in a table

Currently, I have successfully implemented a jQuery autocomplete feature on the text input of a table data element called txtRow1. The data for this autocomplete is fetched remotely from a MySQL database and returned in JSON format as 'value' for ...

Maximizing Efficiency of Vendor Bundle in Angular 2 with Webpack

My MEAN application's client side is built in Angular2 with Webpack, but I'm facing slow loading times due to a large vendor modules JS file. Is there a way to optimize this situation? I want to separate the vendor's JS file. Below is my we ...

Converting JavaScript code to React requires excluding jQuery

I have been working on updating my old JavaScript code to make it compatible with React. The main goal is to integrate external data into a 3rd party form. Here is the original JS code: <script charset="utf-8" type="text/javascript" ...

jQuery Autocomplete - Showing array of options upon selecting input field in Internet Explorer

After encountering an issue with the autocomplete feature in a web application, I posted a question on Stack Overflow. The provided answer solved the problem in Chrome, but unfortunately, it did not work in Internet Explorer 8 or 9, and possibly earlier ve ...

Jquery draggable droppable does not support displaying multiple divs simultaneously

I tried to implement the jquery ui draggable and droppable features to display 3 divs within a designated area. Below is the code snippet: --CSS: #content-1 { width: 200px; height: 100px; border: 1px solid red; display: none; } #content-2 { width: ...