简体   繁体   中英

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 like the dollar sign,minus, and period and so on.

Here is that code, I would like to see if I can combine them into one and be able to check for the validation and replace the key press with a space all in one code/call.

<script type="text/javascript">
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
document.getElementById('limitedtextarea').value=str
//return true;

} 
</script>

<FORM action="sms_SendMessage.asp" method=post onsubmit="javascript:return ValidateForm(this)" target=_blank>

Thanks for the help...

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

function ValidateForm(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;

}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM