Search code examples
javascriptkeycode

Replace comma, dash, and enter key in textarea with space


I want that when user presses a comma, dash, or enter key, the textarea replace will show a space.

This code only works for the enter key.

    $("#site_name").on("keypress",function(e) {
        var key = e.keyCode;
        if ((key == 188)||(key == 13)||(key == 173)||(key == 191)) {
            document.getElementById("site_name").value=document.getElementById("site_name").value + " ";
            return false;
        } else {
            return true;
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea  name="site_name" id="site_name" style="width: 100%;" rows="3"> </textarea>


Solution

  • If you want to continue to use a JavaScript event I would suggest using the keydown event. keydown and keypress will give you different results as they map to different functionality. Comma = 188, dash = 189, enter = 13.

    $("#site_name").on("keydown",function(e) {
        var key = e.keyCode;
        console.log("keycode: " + key);
        if ((key == 189)||(key == 188)||(key == 13)||(key == 173)||(key == 191))              
        {    
            document.getElementById("site_name").value=document.getElementById("site_name").value + " ";
            return false;
        }
        else 
        {
            return true;
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea  name="site_name" id="site_name" style="width: 100%;" rows="3"> </textarea>