Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How Can Calculate HTML Input Values And Show Directly Input Value By JQuery?
There are several JavaScript methods we can use to retrieve the value of the text input field. We can access or set the value of text input fields using the jQuery .val() method. This article demonstrates how to calculate HTML input values and display them directly using jQuery.
The .val() method is particularly useful for retrieving form data in real-time and performing calculations without requiring form submission. This creates a more interactive user experience.
Syntax
Following is the syntax for retrieving input values using the .val() method
$(selector).val()
To set a value, use
$(selector).val(newValue)
Using jQuery val() Method
The .val() method retrieves the values of form elements like input, select, and textarea. It returns undefined when called on an empty collection. This method is essential for dynamic calculations and real-time value updates.
Example Price Calculator with Real-time Updates
Following example demonstrates calculating the final amount by subtracting discount from the actual price in real-time
<!DOCTYPE html>
<html>
<head>
<title>Price Calculator</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.form-group { margin: 15px 0; }
label { display: inline-block; width: 120px; font-weight: bold; }
input { padding: 8px; width: 150px; border: 1px solid #ccc; border-radius: 4px; }
.readonly { background-color: #f8f9fa; }
button { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; background-color: #f0f8ff;">
<h2>Price Calculator</h2>
<form>
<div class="form-group">
<label for="price">Actual Price:</label>
<input type="number" id="price" class="price form-control" placeholder="Enter price" />
</div>
<div class="form-group">
<label for="discount">Discount:</label>
<input type="number" id="discount" class="discount form-control" placeholder="Enter discount" />
</div>
<div class="form-group">
<label for="amount">Final Amount:</label>
<input type="text" id="amount" class="amount form-control readonly" readonly />
</div>
<button type="button">Calculate Total</button>
</form>
<script>
$('form input[type="number"]').on('keyup input', function() {
var price = parseFloat($('#price').val()) || 0;
var discount = parseFloat($('#discount').val()) || 0;
var finalAmount = price - discount;
$('#amount').val(finalAmount.toFixed(2));
});
</script>
</body>
</html>
The output displays a calculator form that automatically updates the final amount as you type in the price and discount fields
Price Calculator Actual Price: [100] ? Enter values here Discount: [20] ? Real-time calculation Final Amount: 80.00 ? Updates automatically [Calculate Total]
Example Live Text Display
Following example shows how to display input text directly on the webpage in real-time
<!DOCTYPE html>
<html>
<head>
<title>Live Text Display</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.display-text {
color: #d63384;
font-size: 18px;
font-weight: bold;
margin-top: 15px;
padding: 10px;
border: 2px dashed #d63384;
background-color: #fff5f5;
min-height: 30px;
}
input { padding: 10px; width: 300px; font-size: 16px; border: 2px solid #ccc; border-radius: 5px; }
</style>
</head>
<body style="font-family: Arial, sans-serif; text-align: center; background-color: #f8f4ff; padding: 30px;">
<h2>Live Text Display Demo</h2>
<input type="text" name="name" id="textInput" placeholder="Type something here...">
<div class="display-text" id="output">Your text will appear here...</div>
<script>
$("#textInput").on('keyup input', function() {
var text = $(this).val();
$("#output").text(text || "Your text will appear here...");
});
</script>
</body>
</html>
The output shows an input field that displays typed text immediately below it
Live Text Display Demo [Type something here...] ? Input field Hello jQuery! ? Text appears instantly as you type
Example Button-triggered Value Display
Following example demonstrates retrieving and displaying input values when a button is clicked
<!DOCTYPE html>
<html>
<head>
<title>Button Value Display</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.container { max-width: 400px; margin: 0 auto; padding: 20px; }
input { padding: 12px; width: 100%; margin: 10px 0; font-size: 16px; border: 2px solid #ddd; border-radius: 6px; }
button { padding: 12px 25px; background-color: #28a745; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; }
button:hover { background-color: #218838; }
.result { margin-top: 15px; padding: 15px; background-color: #d1ecf1; border: 1px solid #bee5eb; border-radius: 6px; }
</style>
</head>
<body style="font-family: Arial, sans-serif; background-color: #e3f2fd; padding: 20px;">
<div class="container">
<h2>Input Value Display</h2>
<input type="text" id="userInput" placeholder="Enter your message">
<button type="button" id="showButton">Show Input Value</button>
<div class="result" id="displayArea" style="display: none;"></div>
</div>
<script>
$(document).ready(function() {
$("#showButton").click(function() {
var inputValue = $("#userInput").val();
if (inputValue.trim() !== "") {
$("#displayArea").html("<strong>You entered:</strong> " + inputValue).show();
} else {
$("#displayArea").html("<em>Please enter some text first.</em>").show();
}
});
});
</script>
</body>
</html>
The output shows an input field with a button that displays the entered value when clicked
Input Value Display [Enter your message] ? Type text here [Show Input Value] ? Click to display You entered: Hello World! ? Result appears below
Key Points
When working with jQuery .val() method for input calculations and display, consider these important points
-
Event handling Use
keyup,input, orchangeevents for real-time updates. Theinputevent is preferred for modern browsers as it captures all input changes. -
Data validation Always validate and sanitize input values before calculations. Use
parseFloat()orparseInt()with fallback values to handle empty or invalid inputs. -
Performance For complex calculations, consider debouncing the input events to avoid excessive calculations on every keystroke.
-
Number formatting Use
toFixed()method to format decimal numbers for currency or precise calculations.
Common Use Cases
The jQuery .val() method is commonly used in the following scenarios
-
Form calculators Price calculations, tax computations, and mathematical operations based on user input.
-
Live search Filtering content as users type in search boxes.
-
Form validation Real-time validation feedback for user inputs.
-
Dynamic content Updating page content based on form field values without page refresh.
Conclusion
The jQuery .val() method provides an efficient way to retrieve and manipulate input field values for real-time calculations and dynamic content updates. By combining it with appropriate event handlers like keyup and input, you can create interactive forms that respond immediately to user input, enhancing the overall user experience.
