Textarea 엔터 이벤트 - Textarea enteo ibenteu

티스토리 뷰

Textarea 엔터 이벤트 - Textarea enteo ibenteu

챗봇형식을 어설프게 따라한 것인데 보통 채팅할 때 버튼이 있어도 엔터키를 눌러서 전송시키는 동작이 일반적이다.

물론 줄바꿈이 반드시 필요한 경우에는 맞진 않겠지만 그 경우를 빼고 생각하였다.

textarea#chatBot(class='form-control' style='resize:none; width:340px; height:300px;' name='chatBot' readonly='readonly') bot : 안녕 내가 도와줄게!

p

textarea#chatUser(class='form-control' style='resize:none; width:340px; height:50;' name='chatUser')

p

input#chatPost(type='button' value='보내기' class='chatsend')

cs

(textarea의 class 부분은 꼭 써주지 않아도 된다. css적인 요소를 약간 넣은 것이다.) 위는 pug 템플릿으로 쓰인 구문이고

https://pughtml.com/ 

위 사이트에서 pug <-> html 간의 변환이 가능하다.

일단 신경써야하는 부분은 엔터키를 눌렀을 때 버튼이 클릭된 것과 동일한 이벤트를 발생시키는 것이다.

[자바스크립트 부분]

script.

document.getElementById('chatUser').addEventListener('keydown',function(event){

if(event.keyCode ==13){

event.preventDefault();

document.getElementById('chatPost').click();

}

});

document.querySelector('.chatsend').addEventListener('click',function(){

document.getElementById('chatBot').value += '\n나 : '+document.getElementById('chatUser').value;

});

cs

보면 사용자가 입력하는 textarea부분에서 keydown 이벤트가 발생했을 때, 그리고 그 key가 13번 (enter키) 일 때 

바로 아래있는 querySelector을 통해 처음에 만들어주었던 button이 클릭되는 이벤트를 실행시키는 과정이다.

채팅창의 내용이 지워지면 안되므로 기존 채팅창에서 더하기를 하여 기존 채팅내용도 없어지지 않고 새로 작성하는 채팅내용도 

줄바꿈의 형태로 들어가는 코드이다. 

맨 위에 짤방처럼 챗봇이 응답하는 형태로 하려면 버튼 click 이벤트에다가 추가적으로 ajax통신 function을 추가적으로 작성해주면 

사용자의 채팅에 응답할 수 있는 형태로 만들 수 있다. 

I have a textarea, On every Enter key pressed in textarea I want new line to be started with a bullet say (*). How to go about it ?

No jQuery please.

I can observe for the Enter key , after that !? Should I have to get the whole value of textarea and append * to it and again fill the textarea ?

Joe

3,1146 gold badges44 silver badges63 bronze badges

asked Jan 20, 2010 at 7:22

1

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

answered Jan 20, 2010 at 7:35

Textarea 엔터 이벤트 - Textarea enteo ibenteu

William TroupWilliam Troup

12.3k21 gold badges67 silver badges95 bronze badges

5

Simply add this tad to your textarea.

onkeydown="if(event.keyCode == 13) return false;"

answered Dec 16, 2012 at 9:44

1

You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup event, as suggested, and use a regular expression to ensure the value is as you require:

<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
    function formatTextArea(textArea) {
        textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
    }

    window.onload = function() {
        var textArea = document.getElementById("t");
        textArea.onkeyup = function(evt) {
            evt = evt || window.event;

            if (evt.keyCode == 13) {
                formatTextArea(this);
            }
        };
    };
</script>

answered Jan 20, 2010 at 9:34

Tim DownTim Down

309k72 gold badges445 silver badges521 bronze badges

2

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

The_Fox

6,9242 gold badges41 silver badges68 bronze badges

answered Nov 2, 2011 at 12:36

0

You could do something like this:

$("#txtArea").on("keypress",function(e) {
    var key = e.keyCode;

    // If the user has pressed enter
    if (key == 13) {
        document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";
        return false;
    }
    else {
        return true;
    }
});
<textarea id="txtArea"></textarea>

answered Feb 24, 2016 at 9:10

1