具有多个输入的JQuery字符计数器 [英] JQuery character counter with multiple inputs

查看:204
本文介绍了具有多个输入的JQuery字符计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一个简单的文本框字符计数器(如Twitter)的解决方案。

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');
            }
        });
    });
});


推荐答案

http://jsfiddle.net/bczengel/tsbfU/

这里有问题。


  1. 代码正在不存在的输入字段上查找maxLength属性。

  2. 如果您使用最新版本的jQuery,则应该使用.on()方法。它有一些其他的功能over bind,但基本上是更新的方法。

  3. 你不需要遍历所有的输入。 jQuery会将你的事件绑定到它在结果集中找到的所有元素。

  4. 我将焦点添加到事件列表,以便在输入输入时更新计数器。您可能需要添加一个单独的模糊事件处理程序,以在没有输入时隐藏计数器。

  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.

这篇关于具有多个输入的JQuery字符计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆