views:

57

answers:

5

I need to create a textarea with jquery and/or javascript.

I am using this code ( click here for preview ) but backspace, enter, simbols and lowercase doesn't work. Why ?:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
<meta charset=utf-8 />
<title>TEST</title>

<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
<![endif]-->

<script type="text/javascript">
<!--

$(document).keyup(function(event) {
  var keyCode = event.keyCode;
  $('#mytext').text(function(i, text) {
      return text + String.fromCharCode(keyCode);
  });

});

// -->
</script>

<style>

  #cmd {
    position: relative; 
    font-family: courier;
    font-weight:bold;
    font-size: 14px;
    padding: 5px;
    overflow: hidden;

  }

  #mytext {
    float: left; 
    padding-left: 3px;
    white-space: pre;
  }


</style>
</head>

<body>

  <div id="cmd">
  <br>
    <div id="mytext">hello </div>

  </div>

</body>

</html>

A: 

For keydown and keyup events, you can identify most common keys (letters, numbers, and a few others) by just looking at the event.keyCode and more or less pretending that it is an ASCII code. However, it isn't really, and the many Javascript manuals that say it can be converted to a character by doing "String.fromCharCode(event.keyCode)" are wrong. On keydown and keyup events, the key codes are not character codes, and this conversion will give wild results for many keys. There is no general portable way to convert keycodes to characters. You pretty much have to sense the browser type and base the key mapping on that.

from http://unixpapa.com/js/key.html

Why don't you use a textarea with some styling?

Thomas Clayson
A: 

return text + String.fromCharCode(keyCode); appends a String to another string. Backspace and other control keys do not append strings, they do something with removing characters/moving caret. In this case, you should handle these keyCodes yourself. You can also designate the content as editable, then the browser handles all the control keys (like a WYSIWYG editor).

See: http://jsbin.com/obuya3/4 for an example

bouke
A: 

Hello

I'm not about your question.

If you want to create a textarea with jquery, there are a lot of ways.

$("#cmd").append("");

Or you want use DOM.

Vinzius
+1  A: 

Why not have those keys call a function to place html in between <div id="cmd"></div>

I could not find a keypress event function but it this should give you an idea

if (keycode==31) {
    $("#cmd").append("<br/>");
}

31 is code for enter.

Look here, they discuss jquery functions on keypress:
http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed

dany
A: 

If you use a HTML5, you can use "contenteditable" property.

Almazzed