jQuery get textarea text
Asked Answered
F

9

527

Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in FPS games, etc.), and then have it Ajax itself back to the server in-order to do stuff.

I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).

I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character?

Fluoric answered 28/9, 2008 at 0:5 Comment(0)
U
762

Why would you want to convert key strokes to text? Add a button that sends the text inside the textarea to the server when clicked. You can get the text using the value attribute as the poster before has pointed out, or using jQuery's API:

$('input#mybutton').click(function() {
    var text = $('textarea#mytextarea').val();
    //send to server and process response
});
Upon answered 28/9, 2008 at 0:17 Comment(5)
Because the textarea would contain more then just the text needed. (it's console, visualize command prompt). Thanks for info on the val function. :)Fluoric
The you can process the text using javascript. What is the point of returning the key stroke codes?Upon
The point is, imo, obtaining the key stroke code would be more efficient then splitting the textarea by a delimiter (picture a possibly large array of text).Fluoric
Sorry, I'm failing to visualize the scenario in which that would be true... maybe if you edited your original post and added an example it would help people trying to answerUpon
I forgot the 'textarea' part infront of the html tag idMessiaen
S
48

Where it is often the text function you use (e.g. in divs etc) then for text area it is val

get:

$('#myTextBox').val();

set:

$('#myTextBox').val('new value');
Sailer answered 13/6, 2014 at 10:32 Comment(0)
B
24

You should have a div that just contains the console messages, that is, previous commands and their output. And underneath put an input or textarea that just holds the command you are typing.

-------------------------------
| consle output ...           |
| more output                 |
| prevous commands and data   |
-------------------------------
> This is an input box.

That way you just send the value of the input box to the server for processing, and append the result to the console messages div.

Balsamic answered 6/7, 2010 at 3:57 Comment(2)
Yes, exactly what I was thinking. It's the only clean solution that doesn't involve either parsing out the input from the output ( foolish to try -- what if the user types over some "output" ), or trying to build up a string from keystroke events ( foolish to try -- what about backspaces, etc? ).Byelostok
Another XY problem on SO. This is clearly the best solution to the 'X' of his problem.Diastyle
N
14

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

Naval answered 28/9, 2008 at 0:11 Comment(1)
I actually hoping a textchanged event or something along the line would be invoked (I could do this pretty easily with the keyup event anyway). I think i will stick to using the keyup event, but do you know of a way to convert the keycode to an ASCII char? Thanks. :)Fluoric
F
8

I have figured out that I can convert the keyCode of the event to a character by using the following function:

var char = String.fromCharCode(v_code);

From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).

Thanks for all your help guys.

Fluoric answered 28/9, 2008 at 0:34 Comment(0)
M
7

Methinks the word "console" is causing the confusion.

If you want to emulate an old-style full/half duplex console, you'd use something like this:

$('console').keyup(function(event){
    $.get("url", { keyCode: event.which }, ... );
    return true;
});

event.which has the key that was pressed. For backspace handling, event.which === 8.

Monjo answered 14/6, 2011 at 14:45 Comment(0)
H
6

you can get textarea data by name and id

// by name
<textarea name="comment"></textarea>
let text_area_data = $('textarea[name="comment"]').val();

// by id
<textarea id="comment" name="comment"></textarea>
let text_area_data = $('textarea#comment').val();
Hatchment answered 31/5, 2020 at 9:0 Comment(0)
S
3

the best way: $('#myTextBox').val('new value').trim();

Superaltar answered 25/11, 2017 at 16:55 Comment(0)
W
0

Read textarea value and code-char conversion:

function keys(e) {
  msg.innerHTML = `last key: ${String.fromCharCode(e.keyCode)}`
  
  if(e.key == 'Enter') {
    console.log('send: ', mycon.value);
    mycon.value='';
    e.preventDefault();
  }
}
Push enter to 'send'<br>
<textarea id='mycon' onkeydown="keys(event)"></textarea>

<div id="msg"></div>

And below nice Quake like console on div-s only :)

enter image description here

document.addEventListener('keyup', keys);

let conShow = false

function keys(e) {
  if (e.code == 'Backquote') {
    conShow = !conShow;
    mycon.classList.toggle("showcon");
  } else {
    if (conShow) {
      if (e.code == "Enter") {
        conTextOld.innerHTML+= '<br>' + conText.innerHTML;
        let command=conText.innerHTML.replace(/&nbsp;/g,' ');
        conText.innerHTML='';
        console.log('Send to server:', command); 
      } 
      else if (e.code == "Backspace") {
        conText.innerHTML = conText.innerText.slice(0, -1);
      } else if (e.code == "Space") {
        conText.innerHTML = conText.innerText + '&nbsp;'
      } else {
        conText.innerHTML = conText.innerText + e.key;
      }

    }
  }
}
body {
  margin: 0
}

.con {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-start;
  width: 100%;
  height: 90px;
  background: rgba(255, 0, 0, 0.4);
  position: fixed;
  top: -90px;
  transition: top 0.5s ease-out 0.2s;
  font-family: monospace;
}

.showcon {
  top: 0px;
}

.conTextOld {
  color: white;
}

.line {
  display: flex;
  flex-direction: row;
}

.conText{   color: yellow; }

.carret {
  height: 20px;
  width: 10px;
  background: red;
  margin-left: 1px;
}

.start { color: red; margin-right: 2px}
Click here and Press tilde ` (and Enter for "send")

<div id="mycon" class="con">
  <div id='conTextOld' class='conTextOld'>Hello!</div>
  <div class="line">
    <div class='start'> > </div>
    <div id='conText' class="conText"></div>
    <div class='carret'></div>
  </div>
</div>
Walking answered 9/4, 2019 at 20:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.