Count Characters in Textarea with jQuery
Counting characters in textarea with jQuery
In web applications, when designing forms for receiving data from users, such as product feedback, etc., it is necessary to allow users to input a limited amount of text. It can help to prevent spam and avoid reading unnecessary long messages. It also saves resources.
So In this blog, you are going to learn shows
how to limit number of characters and display characters left in
textarea while user entering text in the textarea component. It also includes, how to count characters in a text that is entered in a text box using jQuery.
Here is an example.
MOVETOP↑
countcharacters.php
<html> <head> <title>Codingzon Tutorials http://localhost/phpuseful/countchars.php#</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <body bgcolor=""> <center> <br /><br /><br /><br /> <form> <div class="col3"> <h2>Product feedback :</h2> Enter your message. Limit 250 characters.<br /><br /> <textarea cols="40" rows="5" id="message" ></textarea><br> <a id="save" style="padding:7px 0 0 0" href="#">Save Message</a> <div id="textleft">250 characters left</div> </div><br> <div id="data"></div> <script> $(document).ready(function () { $('#message').keyup(function (event) { var max = 250; var len = $(this).val().length; var char = max - len; $('#textleft').text(char + ' characters left'); }); $( "#save" ).on('click',function() { var text = $('#message').val(); $.ajax({ url: "savetext.php", type: "GET", data: { text: text }, cache: false, success: function (response) { $("#data").html(response); // echo "response"; } }); }); }); </script> </body> </html>
savetext.php
This PHP program receives the text using $ajax() jQuery method in above program, when user clicks on save message link.
<?php
$string = $_GET['text'];
echo "Message: ".$string . " Saved "; // it can be stored in database
?>
GO TOP↑
Result:
In this blog, you learn:
How to limit the characters and display the remaining characters and save message in backend using PHP and Ajax.
Comments
Post a Comment