mike_pl mike_pl - 4 months ago 9
Javascript Question

Javascript character counter function with parameters

I am beginner in javascript and I implemented to my EditorFor character counter found somewhere, here is how it looks in code now:

<span class="text-length-counter" id="email_counter"></span>
@Html.EditorFor(model => model.ProfileFormDto.Email, new { htmlAttributes = new { @class = "form-control create-view-field", id="email_area" }})


And here is a javascript function that does the work:

$(document).ready(function() {
var text_max = 50;
var text_length = $('#email_area').val().length;

$('#email_counter').html(text_length +' / ' + text_max + ' znaków');

$('#email_area').keyup(function() {
var text_length = $('#email_area').val().length;

$('#email_counter').html(text_length + ' / ' + text_max + ' znaków');
});
});


It is working fine, but I have to modify this function(), because I have to use many counters at one page, so function above have to take three arguments, like: Count(counter,area,max).I can't manage this. There is my new function declaration in section:

$(document).ready(function () {
Count('email_counter','email_area',50);
});

function Count(counter,area,max) {

var text_length = $('#area').val().length;

$('#counter').html(text_length +' / ' + max + ' znaków');

$('#area').keyup(function() {
var text_length = $('#area').val().length;

$('#counter').html(text_length + ' / ' + max + ' znaków');
});
};


It's not working, I get error:
Manage:169 Uncaught TypeError: Cannot read property 'length' of undefined

Answer

Your jQuery selector is currently trying to select the elements with id="area" and id="counter"

If you're going to turn the area and counter into parameters, you need to select with $('#' + area) and $('#' + counter).

With this update, your code would look like

function Count(counter, area, max) {
  var text_length = $('#'+area).val().length;

  $('#'.concat(counter)).html(text_length +' / ' + max + ' znaków');

  $('#'+area).keyup(function() {
    var text_length = $('#'+area).val().length;
    $('#'+counter).html(text_length + ' / ' + max + ' znaków');
  });
};

Here's a working jsfiddle with multiple input fields.