Giter VIP home page Giter VIP logo

mimo84 / bootstrap-maxlength Goto Github PK

View Code? Open in Web Editor NEW
785.0 43.0 193.0 18.8 MB

This plugin integrates by default with Twitter bootstrap using badges to display the maximum lenght of the field where the user is inserting text. Uses the HTML5 attribute "maxlength" to work.

Home Page: http://mimo84.github.com/bootstrap-maxlength/

License: MIT License

JavaScript 92.49% HTML 7.51%
maxlength javascript bootstrap badge bootstrap-maxlength html5-attribute twitter-bootstrap

bootstrap-maxlength's Introduction

This plugin integrates by default with Twitter bootstrap using badges to display the maximum length of the field where the user is inserting text. This plugin uses the HTML5 attribute "maxlength" to work.

The indicator badge shows up on focusing on the element, and disappears when the focus is lost.

Configurable options

  • alwaysShow: if true the threshold will be ignored and the remaining length indication will be always showing up while typing or on focus on the input. Default: false.
  • threshold: this is a number indicating how many chars are left to start displaying the indications. Default: 0.
  • warningClass: it's the class of the element with the indicator. Default is small form-text text-muted but can be changed to anything you'd like.
  • limitReachedClass: it's the class the element gets when the limit is reached. Default is small form-text text-danger and can be changed.
  • limitExceededClass: it's the class that the element gets when the limit is exceeded. The default is '' In this case, the limitReachedClass setting is used.
  • separator: represents the separator between the number of typed chars and total number of available chars. Default is /.
  • preText: is a string of text that can be outputted in front of the indicator. preText is empty by default.
  • postText: is a string outputted after the indicator. postText is empty by default.
  • showMaxLength: if false, will display just the number of typed characters, e.g. will not display the max length. Default: true.
  • showCharsTyped: if false, will display just the remaining length, e.g. will display remaining length instead of number of typed characters. Default: true.
  • appendToParent: appends the maxlength indicator badge to the parent of the input rather than to the body. Default: false.
  • message: an alternative way to provide the message text, i.e. 'You have typed %charsTyped% chars, %charsRemaining% of %charsTotal% remaining'. %charsTyped%, %charsRemaining% and %charsTotal% will be replaced by the actual values. This overrides the options separator, preText, postText and showMaxLength. Alternatively you may supply a function that the current text and max length and returns the string to be displayed. For example, function(currentText, maxLength) { return '' + Math.ceil(currentText.length / 160) + ' SMS Message(s)'; }
  • utf8: if true the input will count using utf8 bytesize/encoding. For example: the '£' character is counted as two characters. Default: false.
  • showOnReady: shows the badge as soon as it is added to the page, similar to alwaysShow. Default: false.
  • twoCharLinebreak: count linebreak as 2 characters to match IE/Chrome textarea validation. Default: true.
  • customMaxAttribute: String -- allows a custom attribute to display indicator without triggering native maxlength behaviour. Ignored if value greater than a native maxlength attribute. customMaxClass settings gets added when exceeded to allow user to implement form validation. Default is null.
  • customMaxClass: Set the class to be added with 'customMaxAttribute'. The default is 'overmax'.
  • validate: If the browser doesn't support the maxlength attribute, attempt to type more than the indicated chars, will be prevented. Default: false.
  • allowOverMax: Will allow the input to be over the customMaxLength. Useful in soft max situations. Default false.
  • zIndex: Will set the counter z-elevation. Useful to fix elevation in modals or dialogs. Default 1099.
  • placement: Is a string, object, or function, to define where to output the counter.
    • Possible string values are: bottom, left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right. Are also available : bottom-right-inside (default option, as in Google's Material Design), top-right-inside, top-left-inside and bottom-left-inside.
    • Custom placements can be passed as an object, with keys top, right, bottom, left, and position. These are passed to $.fn.css.
    • A custom function may also be passed. This method is invoked with the {$element} Current Input, the {$element} MaxLength Indicator, and the Current Input's Position {bottom height left right top width}.

Events

  • maxlength.reposition on an input element triggers re-placing of its indicator. Useful if textareas are resized by an external trigger.
  • maxlength.shown is triggered when the indicator is displayed.
  • maxlength.hidden is triggered when the indicator is removed from view.

Examples

Basic implementation:

$('[maxlength]').maxlength();

Change the threshold value:

$('input.className').maxlength({
    threshold: 20
});

An example with some of the configurable options:

$('input.className').maxlength({
    alwaysShow: true,
    threshold: 10,
    warningClass: "label label-info",
    limitReachedClass: "label label-warning",
    placement: 'top',
    preText: 'used ',
    separator: ' of ',
    postText: ' chars.'
});

The same example using the message option:

$('input.className').maxlength({
    alwaysShow: true,
    threshold: 10,
    warningClass: "label label-info",
    limitReachedClass: "label label-warning",
    placement: 'top',
    message: 'used %charsTyped% of %charsTotal% chars.'
});

An example allowing user to enter over max characters. NOTE: you cannot have the maxlength attribute on the input element. You will need to provide the customMaxAttribute attribute

Sample HTML element:

<textarea class="form-control" id="xyz" name="xyz" maxlength="10"></textarea>
// Setup maxlength
$('.form-control').maxlength({
	alwaysShow: true,
	validate: false,
	allowOverMax: true,
    customMaxAttribute: "90"
});

// validate form before submit
$('form').on('submit', function (e) {
	$('.form-control').each(
		function () {
			if ($(this).hasClass('overmax')) {
				alert('prevent submit here');
				e.preventDefault();
				return false;
			}
		}
	);
});

An example of triggering a maxlength.reposition event whenever an external autosize plugin resizes a textarea:

$('textarea').on('autosize:resized', function() {
    $(this).trigger('maxlength.reposition');
});

bootstrap-maxlength's People

Contributors

abdullahali avatar antonnguyen avatar ashleyglee avatar darayus avatar dependabot[bot] avatar djibe avatar fntm avatar g-g avatar genu avatar georggell avatar hugoj-goncalves avatar joanpedreno avatar kreegr avatar ledowong avatar maddix avatar maxschulze avatar mbseid avatar mimo84 avatar pnikolov avatar pocketarc avatar tomyam1 avatar vfonic avatar wmassingham avatar y-takey avatar ysrb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bootstrap-maxlength's Issues

Can't overwrite bootstrap css styles

I have a bootstrap theme that sits on top of the framework. Problem is that the theme is being ignored. It's load the styling for the default bootstrap labels. I've changed the colors, font and padding on my theme label classes. If I insert a label right after the input it is rendered properly. Any ideas? DOM loading issue perhaps?

got error when resize window

I am not sure it's a bug or my my failt,
when resizing window, error waw shown like below
"Uncaught TypeError: Cannot call method 'outerWidth' of undefined "

if I focus the input at first, resizing the window will not show this error.

So, at line 276 of source file, I added below

if(maxLengthIndicator === undefined) return;

the error disappeared.

Displays outside of view; add location option

I am using your library for my web-based game data editor, but I ran into an issue with block-level form inputs: the badge was being displayed off the side of the site.

I adjusted the defaults array to have a location: 0 and then changed the focus function to:

currentInput.focus(function() {
    var currentInputTopPx = 0,
    currentInputLeftPx = 0,
    remaining = remainingChars(currentInput, maxLengthCurrentInput);

    manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator)

    switch(options.location)
    {
        case 0: // default, outside bottom right
        {
            currentInputTopPx = currentInput.offset().top + currentInput.outerHeight();
            currentInputLeftPx = currentInput.offset().left + currentInput.outerWidth();
            break;
        }

        case 1: // outside top right
        {
            currentInputTopPx = currentInput.offset().top - maxLengthIndicator.height();
            currentInputLeftPx = currentInput.offset().left + currentInput.outerWidth();
            break;
        }

        case 2: // outside top left
        {
            currentInputTopPx = currentInput.offset().top - maxLengthIndicator.height();
            currentInputLeftPx = currentInput.offset().left - maxLengthIndicator.outerWidth();
            break;
        }

        case 3: // outside bottom left
        {
            currentInputTopPx = currentInput.offset().top + currentInput.outerHeight();
            currentInputLeftPx = currentInput.offset().left - maxLengthIndicator.outerWidth();
            break;
        }

        case 4: // inside centered right
        {
            currentInputTopPx = currentInput.offset().top + (maxLengthIndicator.height() / 2);
            currentInputLeftPx = currentInput.offset().left + currentInput.outerWidth() - maxLengthIndicator.outerWidth() - 3;
            break;
        }
    }

    maxLengthIndicator.css({
        top: currentInputTopPx + 'px',
        left: currentInputLeftPx + 'px',
        zIndex: 999999999
    });
});

Exceeding maximum length

It seems, that different browsers treat newlines differently. For example, Firefox on Mint puts the value \r\n no enter keypress, but counts them as only 1 symbol towards the char-count. Chrome has its own, weird way of doing theses things.

Now, I have created a couple of utility functions, to help me with these cases, and I was wondering, do you want them added? The main question is about the ideology, do we try to manage this length, or leave it up to browsers to deal with this?

Enhancement Request: Add "justified" Placement Options

Great plug-in. Thanks very much for putting it together and making it available.

I'd like to suggest/request some additional "placement" options that would expand on the corner options currently supported. These options would justify the badge/counter with the edge of the input field. So, for example, "bottom-right-justified" would place the badge at the bottom right of the input field (as it currently does) but with the right border of the badge justified with the right border of the input field. Similarly, "top-left-justified" would left justify the left borders of the badge and the field.

Thanks again for a great product.

Allow exceeding maxlength

Hello,

Would it be possible to implement functionality to allow exceeding the maxlength limit?

I assume this would require actually removing the attribute from the document so that the browser does not enforce the limit itself, then use the limit as a criterion only for styling the label.

Thanks

Better do some self protection to avoid duplicated indicator labels when manually call set focus

When I combine "AtWho" plugin with this "maxlength" plugin, I got an issue that a character indicator label is generated whenever there is a "focus" event triggered on the target input/textarea element.

Although, in real world, "blur" event should always triggered naturally first before we can trigger "focus" event again.

However, there will be a lot cases that a developer want to call "focus" to enforce focus behaviour but they forget to check whether the target element is already in focus mode or not.

Thus, it would be better to do a safe protection in this plugin in my opinion.

BTW:
I too have raised an issue to suggest "atWho" plugin to do a check to avoid unnecessary "setFocus".

Suggested Solutions:

1) a new method to safe remove existing indicator if any

                function safeRemoveIndicator() {
                    if (maxLengthIndicator) {
                        maxLengthIndicator.remove();
                        maxLengthIndicator = null;
                    }
                }

2) before create a new one, safe delete it

                currentInput.focus(function () {
                    var maxlengthContent = updateMaxLengthHTML(maxLengthCurrentInput, '0');
                    maxLengthCurrentInput = getMaxLength(currentInput);

                    safeRemoveIndicator();  <-- safe delete existing one if exists

                    maxLengthIndicator = $('<span class="bootstrap-maxlength"></span>').css({
                        display: 'none',
                        position: 'absolute',
                        whiteSpace: 'nowrap',
                        zIndex: 1099
                    }).html(maxlengthContent);

3) safe delete it when blur

                currentInput.blur(function() {
                    safeRemoveIndicator();
                });

Supporting UTF8

Is this support UTF8 characters like chinese,korean,japanese,etc ?

minlength

Is there a way to have a minlength ?
thaks !

pasted text in can cause it to go over the max length

We have noticed that sometimes when you paste text into the the text area it will go over the length by a few characters. It will show for example "603 of 600" and if you delete the 3 characters it will again enforce the limit. While we have not been able to reproduce it consistently it has been experienced by several people on our team.

Documentation page has broken examples

Showing http://mimo84.github.io/bootstrap-maxlength/ to people is a little embarrassing right now, since the examples are broken. One glaring error is the limitReachedClass is set to label label-important which doesn't exist in bootstrap anymore (I believe you want label label-danger), so it just goes away. It's a much easier sell to others when they see it fully working.

If there's a way I can fix this myself, I'd be happy to fork and do it, I just didn't see anything obvious.

input returning as NaN

Hello, I am having an issue where the input is continuously returning "NaN" I have been diving into the source and trying to debug what is actually happening and I am stuck. Here is the setup I have in my main script:

    $('textarea#charCount').maxlength({
        alwaysShow: true,
        threshold: 140,
        warningClass: "label label-info",
        limitReachedClass: "label label-warning",
        placement: 'bottom-right',
        preText: 'used ',
        separator: ' of ',
        postText: ' chars.'
    });

changing screen change max length

  • Define input text with maxlength = 50
  • Initialize bootstrap
  • change Firefox/IE/Chrome with alt TAB at least two times
  • ==> Max length will be changed

Globally, i don't think than it's a good idea to change defined maxlength

i've removed following code and it works :
// Handle the tab press when the maxlength have been reached.
// if (remaining===0 && keyCode===9 && !e.shiftKey) {
// currentInput.attr('maxlength',getMaxLength(currentInput)+1)
// .trigger({
// type: 'keypress',
// which: 9
// }).attr('maxlength',getMaxLength(currentInput)-1);

// }
// if (options.validate && remaining < 0) {
// output = false;
// } else {
manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator);
// }

Add keyCode 9

Check if there are possibilities to add.

Some situations as personal document, the user must press TAB to go to the next field.

Iphone IOS

When typing on ios the counter isn't being updated

Textarea resize

What would be the best way to handle a user resizing the textarea so the indicator moves to the new position?

Append to textarea rather than body

I'm using this with an autogrow plugin for a normal textarea(no wysiwyg). The problem is that when the textarea's height changed whilst typing the position of the counter stays in the same position. If the counter was added to the bottom of the textarea than this would solve the problem. Unless of course you have another solution.

Thanks.

Doesn't count when pasting text

Hi!
When pasting text to text field or textarea it doesn't count the letters. i have to edit the text and only then it starts to count

Thanks!

TypeError: maxLengthIndicator is undefined

Sometimes I get this error and I have absolutely no clue where it is coming from.
I think it could have to do that some of my form fields are hidden, but I can not determine any pattern (I don't get it always on the same page and same code).

TypeError: maxLengthIndicator is undefined
outerWidth = maxLengthIndicator.outerWidth(),

Issue when apply this plugin in a dialog with "position:fixed" and then user scrolls the page.

In my case, I am using bootstrap modal dialog for example, if I have a long page, even with a modal dialog opening, I can still scroll the page body behind.

Then, we will see the character indicator is scrolling along with page body because it is using "position:absolute" for positioning. please see screen shot below.

snip20140211_1

To solve this issue, I did two things together, one thing is the issue #45 which I raised for self protection.

Then, based on #45 , I changed my outside code to listen to the scroll event, when first scroll event happening, I saved the current focused element and call his "blur" event to destroy the label, then, after scroll complete, I called the element with "focus" event to recreate the label, then the new label will take the right position for sure.

However, since in #45 with isolated context, you choose to reuse existing label which means the label's position will not change, thus, that solution can't be used along with this issue.

Anyway, a proposed solution might be:

  1. better plugin internally listen to scroll event, when scroll event starts, hide/destroy the label
  2. when scroll events complete, re-calculate the position and then show/new the label.

Similar code like below

    function HandlingScrolledEvent() {
         // show/new the label
    }

    var timerHandle;
    function throttlingScrollEvents() {
        if(timerHandle) {
            window.clearTimeout(timerHandle);
            timerHandle = null;
        }

       // hide/destroy existing label
        timerHandle = window.setTimeout(HandlingScrolledEvent, 500);
    }

    //listen to global scroll event
    $(window).scroll(throttlingScrollEvents);

Obtain currentInput length

Thanks for the nifty plugin!

I was wondering if there is any way I can obtain the length of the currentInput or 'character count left' value from the onSafeCount() or onOverCount() functions?

Right now, when the counter is over the limit it displays a negative value. I would want to obtain the value and display it as a positive with a changed message, such as: '5 characters over the limit' rather than '-5 characters left'.

Thanks in advance!

Maxlength with dynamically generated text boxes

Hi there, hope you can help.

I am using the plugin on textareas that are being dynamically generated by cloning from a template. The template counter works perfectly (awesome plugin by the way!!!) because it is natively in the html. But when it creates a clone, the elements are generated in the DOM dynamically and so the plugin doesn't work because, I'm thinking, it doesn't recognize the new elements as existing. Am not very familiar with jquery, so wouldn't really know how to create a function to get around this.

Jquery's .on function doesn't seem to work. I tried this by calling it at the bottom of the page it's on:

$(document).on('ready', function() {
        $("textarea").characterCounter({
            limit: 120
        });
    });

I'm pretty sure that's not sematically correct, but I don't have a clue how else to do it. If anyone has any answers, I'd be forever in your debt :)

Thanks!

Not updated character count

If you hold the character, the character count is not updated until it is released or it reaches the limit.

optional restriction of keydown event when char limit reached

Hello,

I need to add an true/false option to plugin for restricting character entry on over reached limit case.

This case is happening on server side value entry on textfields and the remaining character count becomes under zero. Then it is impossible to select a word/sentence and replace it by typing a character.

The first thing that comes to my mind is to fork your project but maybe you can add me to contibuters list and I would be happy to make such developing on base project.

Regards.

Option to completely ignore line breaks

Would it be possible to add an option to ignore line breaks (CR+LF) completely in the character counting (or possibly append this option to Sajus's ignoreBreaks commit)?

Thanks,

demo page

Hello,
If you use https, the demo page is not working. It uses a secure protocol (https) and all the include files are in non-secure protocol (http). Modern browsers does not include unsecure files on secure main file.
2014-05-03_20-46-55

Solution 1: use protocol-relative urls:
instead of

http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js

use

//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js

Solution 2: use secure protocol
instead of

http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js

use

https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js

Regards

Enter key is counted twice.

The logic of inputLength() checks if there is any newline/enter. And if there is any newline or enter it captures this via break counts.

Now the issue with this is that, once I hit enter button, it capture the count as 1+1; Which is incorrect.

Check the below link for the sample demo that I've created, one with ignore breaks and one with considering breaks, try hitting enter and see the count.

http://jsfiddle.net/sajus/Z8Bmn/

Message not refreshing after submitting

The plugin works properly to begin with
image
but if I then send a message
image
image
the characters remaining message doesn't refresh until I either start typing a new message, or receive one.

Create a 'destroy' public method

It would be great if we could completely remove the plugin footprint with a destroy method (like for any jquery UI widget)

$('*[maxlength]').maxlength('destroy');

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.