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

Issues with JQuery .on() occur when functions are passed as arguments

There seems to be a difference in how the .on() function behaves when passing functions as parameters. Interestingly, defining the function inside the parameters versus passing it separately can have different results. An example of this discrepancy is de ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form. You can find a similar example here. submitForm = () => { return this.props.submituserForm() .then(() => { console.log('test') }) ...

Secure communication and client-server API key protection

Looking for advice on building a JS app that communicates with my server using ajax. I need to give the client an api-key for authorization, but sending it through ajax poses security risks as it can easily be replicated by anyone. I don't want to req ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

How can I identify duplicate values within two distinct javascript objects?

Consider two sets of JavaScript arrays containing objects: var allUsers=[{name:"John",age:25},{name:"Emily", age:30},{name:"Michael",age:22}] and var activeUsers=[{name:"John",status:"active"},{name:"Sarah", status:"active"}] I am attempting to iterat ...

Ways to retrieve the neighboring element's value and modify it with the help of JavaScript or jQuery

I am encountering a problem with selecting an adjacent element and updating its value. My goal is to update the input value by clicking the minus or plus buttons. I have successfully retrieved all the buttons and iterated through them, adding onclick eve ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

Error encountered while attempting to locate a WebElement in Webdriver Selenium using Java: java.lang.NullPointerException

My attempt to fetch data from an excel sheet and login to Gmail was partially successful. The browser opened, the desired page loaded, and the login ID was successfully retrieved from the excel sheet and stored in a variable called sUsername. However, I en ...

Tips for detecting and handling errors in user input from the console

Is there a way to catch errors in Chrome's developer tools console when an input throws an error? I attempted using window.addEventListener("error") but it seems that the onerror event listener on window does not capture the console errors. ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

When parameters are included, @Test is disregarded by TestNG

Trying to run a simple test where both Firefox browser and Chrome browser open simultaneously and navigate to the same URL, but encountering an issue where my @Test method is being ignored. However, the @BeforeClass works as expected. Appreciate any help o ...

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

Tips for transferring a JavaScript variable to PHP with AJAX

I am encountering an issue while trying to transfer a JavaScript variable, obtained from clicking a button, to PHP in order to execute a MySQL query. Here is my code: function ajaxCall(nodeID) { $.ajax({ type: "POST", url: "tree.php", data: {activeNode ...

Angular does not always interpret the value returned from a Promise.all call

One of the challenges I'm facing is related to the structure of my controller: controller.things = ['a', 'b', 'c']; controller.loading = true; controller.responses = []; controller.handlePromises = function(){ var pr ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

Having trouble updating the icon on my website using FontAwsome

Just a heads up - I'm not familiar with HTML/CSS/JS. This template is pre-made, and I'm simply making some adjustments to it. Hello, I'm currently working on my portfolio website and I want to display my projects based on the programming la ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

`Finding specific components or pages within an AngularJS application`

I came across a unique webpage for an Angularjs based project. I am looking to develop an autofiller and autoclicker feature. To achieve this, I need to identify pages or subpages uniquely (especially in cases of Ajax-based changes). The major challenge ...

Mac OS reports an Illegal instruction: 4 error when running NodeJS

Each time I try to execute my program, it gives me an Illegal instruction: 4 error without any clue as to why. The code snippet in question: glob('/path/music/*.mp3', function(error, files) { for(var i = 0; i < files.length; i++) { songs ...