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
Selected Reading
How to get the content of a textarea using jQuery?
In jQuery, you can easily retrieve the content of a textarea element using the val() method. This method returns the current value of form elements, including textareas.
Basic Syntax
The basic syntax to get textarea content is −
var content = $("#textareaId").val();
Example
Here is a complete example using one textarea and one button. The textarea is used for user input, then clicking the button displays the value in an alert box −
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
var textareaContent = $("#txt").val();
alert("Textarea content: " + textareaContent);
});
});
</script>
</head>
<body>
<div>
<h3>Enter some text:</h3>
<textarea id="txt" rows="5" cols="30" placeholder="Type your message here..."></textarea>
<br><br>
<button type="button" id="btn">Get Textarea Content</button>
</div>
</body>
</html>
How it Works
The code works as follows −
- $(document).ready() ensures the code runs after the DOM is fully loaded
- $("button").click() attaches a click event handler to the button
- $("#txt").val() retrieves the current content of the textarea with id "txt"
- alert() displays the retrieved content in a popup dialog
This method works for both empty and filled textareas, returning an empty string if no content is present. The val() method is the most reliable way to get form element values in jQuery.
Advertisements
