Is it possible to invoke a Java function from a text box on an HTML page?

For a web project using JSP, MySQL, AJAX with Netbeans and MySQL, I have three textboxes. Two textboxes are for user input, and the third should display the product of the two input values.

How can I achieve this? Should I make an AJAX call or can I call a Java function in the third textbox?

The code is as follows:

<input type="text" value="" name="quantity"/>
</td><td><input type="text" value="" name="price"/>
</td><td><input type="text" value="" name="total"/>

In the value attribute of the textbox named "total", can I call a Java function like value="getTotal()"? If so, how can I access the other two values?

Alternatively, should I make an AJAX call?

Answer №1

Skip using Java functions and opt for client-side scripting instead.

  <td><input type="text" value="" name="quantity" onblur="Calculate()"/>
  </td><td><input type="text" value="" name="price" onblur="Calculate()"/>
  </td><td><input type="text" value="" name="total"/>


  <script type="text/javascript">

  function Calculate()
  {

       var txt1 = document.getElementById("quantity");
       var txt2 = document.getElementById("price");
       var txt3 = document.getElementById("total");
       if ((txt1.value != "") && (txt2.value != ""))
       {
            txt3.value = parseInt(txt1.value) * parseInt(txt2.value); 
       }

  }

  </script>

Make the total textbox read-only or consider using a label instead.

Thank you

Answer №2

If you're looking to perform a basic calculation like the one you described, it can easily be achieved using straightforward JavaScript. Simply include the following code snippet in your script:

function calculateTotal(){
 var quantity = document.getElementById("quantity").value;
 var price = document.getElementById("price").value;
 var total = parseInt(quantity, 10) * parseFloat(price);
 document.getElementById("total").value = total;

Then, update your HTML input field to trigger the JavaScript function whenever there is a change:

<input type="text" value="" id="quantity" onchange="calculateTotal()"/> 

It's important to note that making a server call for a simple calculation like this is not recommended.

Answer №3

Consider utilizing jQuery for dynamic text box value setting based on user input in other fields. I successfully incorporated this feature in a recent shopping cart project for a client. Additionally, jQuery offers a .ajax() method that is user-friendly.

For more information, explore the following resources:

http://docs.jquery.com/How_jQuery_Works

http://api.jquery.com/category/ajax/

Unfortunately, I'm unable to provide a coded response at the moment. I hope this information is still helpful for you.

Answer №4

  <HTML>
  <HEAD>
 <TITLE></TITLE>
     <script type="text/javascript">

     function Multiply()
      {

       var input1 = document.getElementById("FirstNumber");
       var input2 = document.getElementById("SecondNumber");
       var result = document.getElementById("Result");
       if ((input1.value != "") && (input2.value != ""))
       {
            result.value = parseInt(input1.value) * parseInt(input2.value); 
       }

      }

    </script>

 <input id="FirstNumber" type="text" value="" onblur="Multiply()" style="width:50px"/> * 
 <input id="SecondNumber" type="text" value="" onblur="Multiply()" style="width:50px"/>
 <input id="Result" type="text" style="width:50px"/>
 </FORM>
 </BODY>
 </HTML>

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

What is the best method for implementing page transitions between components in NextJS?

My goal is to create a form that smoothly slides to the right, similar to the one seen on DigitalOcean's website when you click "Sign up using email" here: . While the transition itself is relatively simple, I noticed that DigitalOcean uses 2 separat ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

Twilio - encountering difficulties processing phone number upon submission

I clicked on this link to follow the tutorial (you can find it via twilio.) and after completing all the necessary steps, I encountered an issue. Upon running localhost and entering a phone number, I did not receive any text message and the verification wi ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Unable to use onSubmit with enter key in render props (React)

I am looking to include a button within a form that can trigger the onSubmit event when the user presses the Enter key. Here is an example of a functional solution: <form onSubmit={() => console.log('ok')}> <button type="submi ...

Building a Loading Bar with Two Images Using JavaScript and CSS

I am currently experimenting with creating a progress bar using two images: one in greyscale and the other colored. My goal is to place these two divs next to each other and then adjust their x-position and width dynamically. However, I'm having troub ...

Elements on the page appear and disappear as you scroll down

Whenever my scroll reaches the bottom of element B, I want my hidden sticky element to appear. And when I scroll back up to the top of element B, the sticky element should be hidden again. Here are my codes: https://i.sstatic.net/J49dT.jpg HTML <htm ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

The website that had been functioning suddenly ceased operations without any modifications

It seems like this might be related to a JavaScript issue, although I'm not completely certain. The website was working fine and then suddenly stopped. You can find the URL here - Below is the HTML code snippet: <!DOCTYPE html> <html> ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

Can Express POST / GET handlers accommodate the use of jQuery?

I created a simple Express server to retrieve data from an HTML form and make queries to OpenWeatherMap using that data: const { OpenWeatherAPI } = require("openweather-api-node"); const express = require("express"); const bodyParser = ...

Comparisons do not function properly with IFNULL on DATETIME data

Below is the schema that I am working with: CREATE TABLE records ( startDate DATETIME, endDate DATETIME ); INSERT INTO records (startDate, endDate) VALUES ('2017-01-01', NULL); Below is the SQL query I am trying to execute on this sche ...

What methods can I use to distinguish a status and perform functions in PHP MySQL?

My goal is to determine the status of a record as either 0 or 1. In order to achieve this, I am trying to use the code below to check if a specific item with barcode 'D189404954' is in stock. If it is, then perform certain actions, otherwise do ...

Customize the size of data points on your Angular 2 chart with variable

In my Angular 2 application, I am utilizing ng2-charts to create a line chart. The chart functions properly, showing a change in color when hovering over a point with the mouse. However, I want to replicate this behavior manually through code. Upon clicki ...

What is the best approach to animating a specified quantity of divs with CSS and javascript?

How neat is this code snippet: <div class="container"> <div class="box fade-in one"> look at me fade in </div> <div class="box fade-in two"> Oh hi! i can fade too! </div> <div class="box fade-in three"& ...

Sum the total transaction amount from individual subqueries in SQL on a monthly basis

I'm struggling to calculate the total monthly sum of amount tendered from both shop1 and shop2 tables, as well as the monthly total sum of payment amounts from the payments table. If there are no values for a specific month in the payments table, it s ...

Creating a single row on the Wordpress options page with a colspan in the first row

On my WordPress options page, I am utilizing the Fluent Framework to create fields. This framework is quite similar to Meta Box, as both make use of the do_settings_fields function to generate code like the following: <table class="form-table"> < ...

Converting CSS into jQuery

I am exploring ways to create a collapsible section with arrow icons (right and down arrows) in jQuery or JavaScript. Can anyone provide guidance on how to convert my CSS styling into jQuery code? Below is the jQuery approach I have attempted: $(document ...

What is the best way to elegantly finish a live CSS animation when hovering?

Currently, I am working on a planet orbit code where I want to enhance the animation speed upon hover. The goal is for the animation to complete one final cycle at the new speed and then come to a stop. I have been successful in increasing the speed on hov ...

Conditionally defining variables in JavaScript only if they are currently undefined

I have been working on extracting two keywords from a URL in the following format: localhost:3000/"charactername"/"realmname" My goal is to extract "charactername" and "realmname" and assign them to variables. Here is the code snippet I am using: var c ...