1

I've just noticed, that the jQuery text(...) method only sets the content of a TEXTAREA, if if has not been updated manually. For example (also on jsFiddle):

$('#myButton').click(function() {
   $('#myText').text(Date.now); 
});
<textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script>

Now when I click on Go!, the content of the TEXTAREA gets updated with the current timestamp. I also can do it multiple times. Working. But if I manually change the text (e.g. by deleting or adding a character), it stops working.

I also tried out the val(...) method. It works as expected, regardless of manual changes on the text field.

How to get jQuery.text(...) working after manual changes?

automatix
  • 14,018
  • 26
  • 105
  • 230
  • Is there a reason you need to use `.text()` instead of `.val()` here? – j08691 Dec 07 '17 at 17:46
  • *"I also tried out the val(...) method. It works as expected, regardless of manual changes on the text field."* Then why are you using `text`? – T.J. Crowder Dec 07 '17 at 17:48
  • Similar question has been answered here https://stackoverflow.com/questions/1927593/cant-update-textarea-with-javascript-after-writing-to-it-manually – Jaskaran Singh Dec 07 '17 at 17:49
  • @j08691 The `.val(...)` is intended for the `value` attribute. And the `TEXTAREA` has an inner text. So it would make sense to use `.text(...)` for it I just want to know, why it doesn't work as it should or/and whether I'm doing something wrong. – automatix Dec 08 '17 at 13:43
  • @T.J.Crowder Please see the [comment above](https://stackoverflow.com/questions/47700848/how-to-force-jquery-text-working-even-after-manual-updating-the-textarea-value?noredirect=1#comment82391246_47700848). – automatix Dec 08 '17 at 13:44
  • @automatix: `val` isn't intended for the `value` **attribute**, it's intended for the form control's *current value* (the `value` attribute isn't the current value, not even for an `input`; it's the *default* value). What you're doing wrong is using `text`, not `val`. `val` is how you set the value of a `textarea`. If you have any doubt that `val` correctly sets the value of the `textarea`, here's proof: https://jsfiddle.net/msrgzozm/ – T.J. Crowder Dec 08 '17 at 13:51

1 Answers1

0

Your question seems to suggest you know you can use val but are choosing not to. So I tried various options, but I don't think you can reliably use text to set a textarea.

So, since the correct way to set the value of a textarea is to use val, use val. :-) If you do that, it works regardless of whether the textarea is edited by the user:

$('#myButton').click(function() {
   $('#myText').val(Date.now); 
});
<textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875