Hi, 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 plz. 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 ?
A:
You may take a look at some scripts to insert text at cursor position.
Darin Dimitrov
2010-01-20 07:28:50
A:
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.
williamtroup
2010-01-20 07:35:01
@williamtroup: I turned on code formatting for the code.
Tim Down
2010-01-20 09:18:22
This will only work in IE: `window.event` is not supported in other browsers.
Tim Down
2010-01-20 09:35:55
A:
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>
Tim Down
2010-01-20 09:34:45