Skip to content Skip to sidebar Skip to footer

Replace Line-breaks By Spaces Using Javascript

I want to see if it's possible to block the enter key and replace it with a space. I'm also using form validation to only allow letters, numbers and some other specific characters

Solution 1:

In javascript, the line-break character is represented by \n. You could replace them by spaces in your validation function like this :

functionValidateForm(form)
{
    var str
    str=document.getElementById('limitedtextarea').value
    str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
    str=str.replace(/\n/g, " ");
    document.getElementById('limitedtextarea').value=str
    //return true;

}

Solution 2:

If you remove the onsubmit and do not have a submit button, typing enter will not submit it.

<body><form><textarea></textarea></form><script>
(function(){
    var txt = document.getElementsByTagName('TEXTAREA')[0];
    txt.onkeypress = function(ev){
        ev = ev || window.event;
        if ( ev.keyCode === 13 ){
            if (window.event) {
                window.event.returnValue = false;
            }
            if (ev && ev.preventDefault) {
                ev.preventDefault();
            }
            txt.value += ' ';
        }
    };
})();
</script></body>

Post a Comment for "Replace Line-breaks By Spaces Using Javascript"