dcsimg
www.webdeveloper.com
Results 1 to 2 of 2

Thread: insert space every key-press in textbox

  1. #1
    Join Date
    May 2017
    Posts
    1

    insert space every key-press in textbox

    Hi Buddy,

    Actually Iím a new in JavaScript and I donít know how to deal with it. Anyway, Iím very good in HTML and CSS. I really need your help in simplifying the thing for me.
    Actually I have a textbox in the web page and I need the user when they insert CHARACTER will give automatically space after each letter when (onkeypress). How can I apply this technique. Thanks for your help and support.

  2. #2
    Join Date
    May 2016
    Location
    Southern California
    Posts
    81
    You should probably use jquery for this, it's easier to implement and you can use the on input event (changes to input text) instead of onkeypress (any keypress triggers function).

    You will need jquery with this example. Include jquery library into your document and assuming inputField is the id of your input; add this code before your closing </body>:
    HTML Code:
    <script>
        $(document).ready(function () {
            $('#inputField').on('input', function () {
                var self = $(this),
                        currentVal = self.val().replace(/^\s+/, ""), // no spaces in front of letter
                        newVal = removeExtraSpaces(currentVal.split('').join(' ')); // append space to previous character.
                // change the input to our new input value with spacing
                self.val(newVal);
            });
    
        });
        // a hack to prevent having extra spaces side by side if user deletes a letter
        function removeExtraSpaces(string) {
            return string.replace(/\s{2,}/g, ' ');
        }
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles