简体   繁体   中英

filtering value in textarea in 'input' event

What I want is filtering user's input. remove newline and limit its length.

I tried two method.

https://jsfiddle.net/mj111/356yx1df/3/

html

<div>
<textarea id="text1" placeholder="write down"></textarea>
</div>

<div>
<textarea id="text2" placeholder="write down"></textarea>
</div>

script

document.getElementById('text1')
.addEventListener('input', function (evt) {
 evt.preventDefault(); // prevent value change

 const msg = evt.target.value.replace(/\n/g, '')
 if (msg.length <= 10) {
   document.getElementById('text1').value = msg
 }
})

document.getElementById('text2')
.addEventListener('input', function (evt) {
 const msg = evt.target.value.replace(/\n/g, '').slice(0, 10)
 document.getElementById('text2').value = msg
})

first one is not working. because preventDefault is not working. as mdn doc says . 'input' event is not cancelable.

so, I tried second method. just overwrite textarea value.

I think there's a better way to do this. If anyone have good idea, please answer.

use keyup event to limit length or you can just add maxlength manually to the HTML as an attribute. If you want to set it dynamically you can use Element.setAttribute. For preventing new lines you can prevent the return key, as long as it is not shift. You can still use replace to replace things you feel need replacing, a regular expression will most effectively get the job done.

 var text = document.getElementsByTagName('textarea'); var text1 = text[0]; var text2 = text[1]; text1.addEventListener('keydown', function(event) { let val = event.target.value; let limit = 25; // limit the value once you reach a particular length if (val.length > 3) { event.target.value = val.substr(0, limit) }; // prevent new line by preventing enter key press if (event.keyCode === 13 && !event.shiftKey) { event.preventDefault(); alert('no new lines please'); return false; } // and you can filter with replace }) 
 <div> <textarea id="text1" placeholder="write down"></textarea> </div> <div> <textarea id="text2" placeholder="write down"></textarea> </div> 

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