Skip to content Skip to sidebar Skip to footer

Block Characters From Input Text Field, Mirror Input Into Span Or Div

I have some html
The rules for entry into the field: Letters A-Z a-z 0-9 space and d

Solution 1:

I tested the following in Firefox, Safari and Internet Explorer. Unless I didn't fully understand your objective, I believe this should solve your problem.

I ended up writing a jQuery plugin to handle the input caret position. The plugin source is included below, or available on the jQuery plugin site (http://plugins.jquery.com/project/caret-range).

$(document).ready(function () {
    varInvalidPattern = /[^a-z0-9\- ]+/gi;
    varSpacePattern = / /g;

    var name = $("#name");
    var preview = $("#preview");

    var callback = function (e) {
        setTimeout(function () {
            // Get range and length to restore caret positionvar range = name.caret();
            var len = name.val().length;

            // Blur element to minimize visibility of caret jumping
            name.get(0).blur();

            // Remove invalid characters, and update preview
            name.val(name.val().replace(InvalidPattern, ""));
            preview.text(name.val().replace(SpacePattern, "-"));

            // Restore caret positionvar diff = len - name.val().length;
            name.caret(range.start - diff, range.end - diff);
        }, 0);
    };

    name.keypress(callback);
    name.keydown(callback); // Needed by IE to update preview for Delete and Backspace
});

/*
 * jQuery Caret Range plugin
 * Copyright (c) 2009 Matt Zabriskie
 * Released under the MIT and GPL licenses.
 */
(function($) {
    $.extend($.fn, {
        caret: function (start, end) {
            var elem = this[0];

            if (elem) {                         
                // get caret rangeif (typeof start == "undefined") {
                    if (elem.selectionStart) {
                        start = elem.selectionStart;
                        end = elem.selectionEnd;
                    }
                    elseif (document.selection) {
                        var val = this.val();
                        var range = document.selection.createRange().duplicate();
                        range.moveEnd("character", val.length)
                        start = (range.text == "" ? val.length : val.lastIndexOf(range.text));

                        range = document.selection.createRange().duplicate();
                        range.moveStart("character", -val.length);
                        end = range.text.length;
                    }
                }
                // set caret rangeelse {
                    var val = this.val();

                    if (typeof start != "number") start = -1;
                    if (typeof end != "number") end = -1;
                    if (start < 0) start = 0;
                    if (end > val.length) end = val.length;
                    if (end < start) end = start;
                    if (start > end) start = end;

                    elem.focus();

                    if (elem.selectionStart) {
                        elem.selectionStart = start;
                        elem.selectionEnd = end;
                    }
                    elseif (document.selection) {
                        var range = elem.createTextRange();
                        range.collapse(true);
                        range.moveStart("character", start);
                        range.moveEnd("character", end - start);
                        range.select();
                    }
                }

                return {start:start, end:end};
            }
        }
    });
})(jQuery);

Solution 2:

After tinkering around I have refactored my previous solution. This version should behave identical to Twitter. I am keeping my old answer alive simply b/c it is technically valid, and this allows comparing the different approaches.

$(document).ready(function () {
    varSpacePattern = / /g;

    var name = $("#name");
    var preview = $("#preview");

    var updatePreview = function () {
        preview.text(name.val().replace(SpacePattern, "-"));
    };

    name.keypress(function (e) {
        if (e.which > 0 && // check that key code exists
            e.which != 8 && // allow backspace
            e.which != 32 && e.which != 45 && // allow space and dash
            !(e.which >= 48 && e.which <= 57) && // allow 0-9
            !(e.which >= 65 && e.which <= 90) && // allow A-Z
            !(e.which >= 97 && e.which <= 122)   // allow a-z
            ) {
            e.preventDefault();
        }
        else {
            setTimeout(updatePreview, 0);
        }
    });

    name.keyup(updatePreview); // Needed by IE for Delete and Backspace keys
});

Solution 3:

Try this: 1. When key down, copy the previous TextField value. 2. When key up, use RegEx to validate the text (something like /^[a-zA-Z0-9 -]*$/), if unmatch, replace the value with the old one.

Here is the code:

varValidPattern = /^[a-zA-Z0-9\- ]*$/;
$(document).ready(function(){
    $('#name').keydown(function(e) {
        var aValue = $('#name').val();
        $('#name').attr("oldValue", aValue);

        returntrue;
    });
    $('#name').keyup(function(e) {
        var aValue   = $('#name').val();
        var aIsMatch = aValue.search(ValidPattern) != -1;
        if(aIsMatch) {
            $('#preview').text(aValue);
        } else {
            var aOldValue = $('#name').attr("oldValue");
            $('#name')   .val (aOldValue);
            $('#preview').text(aOldValue);
        }
    });
});

Try it.

Solution 4:

I think the best method will be to keep a button and after entering the text inside the text box and clicking on the button show it in the div. It will be much more easier and user friendly.

It would be better not to try hindering the default actions of a user with the keyboard.

Post a Comment for "Block Characters From Input Text Field, Mirror Input Into Span Or Div"