Friday, November 16, 2012

Collection : Javascript : Validating max length

There are some scripts/ functionalities which are commonly and mostly used in many web based applications. I would like to keep some in the collection with us. These might be simple for the readers but are very important to make a note of it.

In this post I will keep note of 1 javascript function which restricts the user by adding more than the specific limit for the input. Or validating the input for certain limit to enter.

In Javascript file
/* check_the_max_length(input, maxLen) 
  input  : need a id or class of input
  maxLen : IE do not accept maxlength so passing it as a parameter.
function check_the_max_length(input, maxLen){
  var val = $(input).val();
  var left = maxLen - val.length;
  var remaining_points = left<=0 ? 0 : left
  $('#counter').html(remaining_points + '/' + maxLen);
  if (val.length >= maxLen) {
      $(input).val(val.slice(0, maxLen));
Considering in view
<%= f.input :description, :as => :text, :input_html => {:style => "width:450px;"}
I added some javascript in views, as application's most of the views are on popups. In main view, where popups will get displayed, add following lines at bottom in script tag.
$('#description').live('keyup keydpress', function(e) {
  check_the_max_length('#description', 220);
As we read, for IE, maxlength was not working, there was another bug. while entering paragraphs it do no calculate properly. For example: if I enter 4 paras the count will show I still have 4 values to enter. But max length attribute actually do not let you enter the value. So removed the maxlength attribute from views for inputs and added slice method which will actually cut down the text to original required count. SO the above function is the solution for both bugs.

No comments:

Post a Comment