2010-06-28 7 views
0

사용자가 입력 할 수있는 텍스트 상자가 있습니다. 그들이 enter를 치면 입력을 확인하고 캐리지 리턴을 \n으로 바꿉니다. 그러나 그것은 여전히 ​​나의 DB에 캐리지 리턴을 보냅니다. 무엇이 잘못 될 수 있습니까? 여기 자바 스크립트 텍스트 상자 새 줄 바꾸기

코드입니다 :

var pp = comment.value; 
alert(pp.replace(/\r?\n|\r/g, "\n")); 
comment.value = pp.replace(/\r?\n|\r/g, "\n"); 

내 DB에 나는 아직도 내가 그것을 대체하고있다하더라도 캐리지 리턴 문자를 얻을.

+0

당신이 "저장"무슨 뜻인지 명확 수 : 당신은 모든 \r\n로 변경 replace 방법을 사용할 수 있습니까? 데이터베이스, 파일, 클라이언트 측 저장소 또는 전혀 다른 것을 말하고 있습니까? –

+0

나는 클라이언트 측을 의미합니다. db로 보내기 전에 – Autolycus

+0

어떤 플랫폼을 사용하고 있습니까? 파이어 폭스 3.6.3/리눅스에서는, 줄의 끝에'\ n' 문자 만 이미 표시되어 있습니다. –

답변

1

, 당신은 그것을 전송하기 전에 텍스트 영역 요소의 내용을 변경할 수 있습니다.

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset=utf-8> 
    <title>Replace carriage returns in textarea</title> 
</head> 
<body> 
    <form id="theForm"> 
    <textarea id="theTextarea" name="txtarea" rows=10 cols=50></textarea> 
    <input type="submit" value="Send"> 
    </form> 
    <script> 
    function replace_newlines() { 
    var textField = document.getElementById("theTextarea"); 
    var textString = textField.value; 
    textField.value = textString.replace(/\r/g, "\n"); 
    } 

    document.getElementById("theForm").onsubmit = replace_newlines; 
    </script> 
</body> 
</html> 
1

다음은 순수한 자바 스크립트에서 사용하는 예입니다.하지만 jquery와 같은 것을 사용하는 경우 훨씬 더 깨끗합니다. 당신이 당신의 폼에 onsubmit 핸들러를 설정하면

<html> 
<head> 
</head> 
<body> 
<textarea id='txt'></textarea> 
<script type='text/javascript'> 
    var txtarea = document.getElementById('txt'); 
    txtarea.onkeypress = keyHandler; 
    function keyHandler(e){ 
     if (document.all) { e = window.event; } 
     if (document.layers || e.which) { pressedKey = e.which; } 
     if (document.all) { pressedKey = e.keyCode; } 
     if(pressedKey == '13'){ 
      txtarea.value = this.value + '\\n'; 
      return false; 
     } 

    } 
</script> 
</body> 
</html> 
+0

당신은'document.all'을 테스트하고 있고 당신이 다루고있는 IE라고 결론을 내리고 있습니까? 이것이 브라우저 감지의 잘못된 방식입니다. 차라리 [기능 감지] (http://www.nczonline.net/blog/2009/12/29/feature-detection-is-not-browser-detection/)를 사용하십시오. 또한'var'을 사용하여 변수를 지역적으로 선언하십시오. 이제 앞에서 선언 한'e'를 덮어 씁니다 :'var e = e || –

+1

e는 함수에 대한 매개 변수이기 때문에 이미 "선언"되어 있으며 함수의 로컬 범위 내에있는 것으로 간주됩니다. –

+0

@ 라이언 : 맞습니다. 'e'는 있지만'pressedKey'는 아닙니다. –

관련 문제