65.9K
CodeProject is changing. Read more.
Home

Show Remaining Characters in Textarea/Input

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (3 votes)

Apr 25, 2017

CPOL
viewsIcon

4874

In a recent user support request, the user would like to see the remaining characters allowed for data input in a text input. This is not a phpGrid standard feature. How can it be achieved? Custom event comes to rescue!

input char counter

In a recent user support request, the user would like to see the remaining characters allowed for data input in a text input. This is not a phpGrid standard feature. How can it be achieved?

Custom event comes to rescue!

First of all, we must insert a new html node for our counter right after the text input. In our demo, we use the “status” field. The new counter will display the text of remaining allowed characters for data entry.

<span id='counter'></span>

We bind a new “onkeyup” JavaScript event to the “status” text input. The phpGrid event you should use is “jqGridAddEditAfterShowForm” so that the counter is only displayed AFTER the form is shown.

$afterShowForm = <<<AFTERSHOWFORM
			function ()
			{
			    $("#tr_status > td.CaptionTD + td.DataTD").append("<span id='counter'></span>");   
			    $("#status").attr("onkeyup","updateCounter()");
			}
			AFTERSHOWFORM;
							$dg->add_event('jqGridAddEditAfterShowForm', $afterShowForm);

We use the CSS selector to style our counter. Most importantly, we make sure it is displayed in the right place (at the end of the text input box).

/* move the counter atop */
							#counter{
			    font-size: 8px;
			    position: relative;
			    top: -15px;
			    float: right;
			    padding-right: 25px;
			    display:inline-block;
							}

Lastly, insert the javascript function below that updates our counter during each key press.

// show how much characters in "status" field input. Max is 10
							function updateCounter() {
			  var maxChar = 10;
			  var pCount = 0;
			  var pVal = $("#tr_status > td.CaptionTD + td.DataTD  input").val();
			  pCount = pVal.length;
			  $("#counter").text(pCount + '/' + maxChar);
							}

Run Live Demo! (Click “Status” input box, and start typing)

The post Show Remaining Characters in Textarea/Input appeared first on phpGrid.