Replace line-breaks by spaces using javascript

旧时模样 提交于 2019-12-23 21:26:58

问题


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...


回答1:


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;

}



回答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>


来源:https://stackoverflow.com/questions/7933623/replace-line-breaks-by-spaces-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!