JQuery character counter with multiple inputs

2019-04-13 10:21发布

I found the solution below to a simple textbox character counter (like Twitter).

Rather than use a single textbox, I've been trying to amend the code to accommodate multiple text inputs without success.

The reason is because I want to validate a URL and text before sending them as the same tweet.

Can anybody point me in the right direction?

<span class="counter"></span>
<input type="text" name="field1" id="field1" class="word_count" />
<input type="text" name="field2" id="field2" class="word_count" />

js:

$(document).ready(function () {
    $('.word_count').each(function () {
        var $this = $(this);
        var counter = $this.parent().find('.counter');
        var maxlength = $this.attr('maxlength');

        counter.text('Only ' + maxlength + ' characters allowed');

        $this.bind('input keyup keydown', function () {
            var value = $this.val();

            if (value.length > 0) {
                counter.text((maxlength - $this.val().length) + ' characters left');
            } else {
                counter.text('Only ' + maxlength + ' characters allowed');
            }
        });
    });
});

1条回答
\"骚年 ilove
2楼-- · 2019-04-13 10:56

First of all here's the fiddle. http://jsfiddle.net/bczengel/tsbfU/

Here were the issues.

  1. The code is looking for a maxLength attribute on the input fields that was not present. Hence the NaN messages.
  2. If your using the latest version of jQuery you should be using the .on() method. It has a few other features over bind but basically its the newer method.
  3. You don't need to iterate over all of the inputs. jQuery will bind your events to all elements it finds in its result set. Basically you were creating a new function for each input when only one was necessary.
  4. I added focus to the list of events so that the counter was updated when you entered an input. You may want to add a separate blur event handler to hide the counter when no input is focused.
查看更多
登录 后发表回答